0

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.

3
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by snippsat
0

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.

0
>>> 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 by snippsat: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.