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.

>>> 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.

Edited 6 Years Ago by snippsat: n/a

This question has already been answered. Start a new discussion instead.