Hi everyone, I'm making some kind of game in Python and i need to save random number to text file but i cant. Please help me out. Here is the code:

def lvl():
    x = random.randint(100,1000)
    tfile = open("text.txt", 'w')
    tfile.write(x)
    input("")

Without x everything is good, but i need to save variable. Thanks.

The error message you receive helps who is trying to help you. Try to post it next time.

But, since your error is easy, here it goes:

def lvl():
    x = random.randint(100,1000)
    tfile = open("text.txt", 'w')
    tfile.write(str(x))
    input("")

Cheers and Happy coding.

Omg thank you very much.

>>> tfile = open("text.txt", 'w')
>>> help(tfile)  

 |  write(...)
 |      write(str) -> None.  Write string str to file.
 |      
 |      Note that due to buffering, flush() or close() may be needed before
 |      the file on disk reflects the data written.

As you see write takes string as an argument,so if you try to put in an integer you get an error.
That error message is pretty clear first part TypeError: must be string,should be a good hint.
Beat_Slayer has the easy soultion to this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.