简体   繁体   中英

Problems with writing and reading files in python

i need to write and read multi variables in one text file

myfile = open ("bob.txt","w")
myfile.write(user1strength)
myfile.write("\n")
myfile.write(user1skill)
myfile.write("\n")
myfile.write(user2strength)
myfile.write("\n")
myfile.write(user2skill)
myfile.close()

at the moment it come's up with this error:


Traceback (most recent call last):
File "D:\\python\\project2\\project2.py", line 70, in <module>
myfile.write(user1strength)
TypeError: must be str, not float

write accepts strings. So you can construct a string and then pass it all at once.

myfile = open ("bob.txt","w")
myfile.write('\n{}\n{}\n{}'.format(user1strength, user2strength, user2skill))
myfile.close()

Also, if your python has support for with , you can do this:

with open("bob.txt", "w") as myfile:
    myfile.write('\n{}\n{}\n{}'.format(user1strength, user2strength, user2skill))

# code continues, file is closed properly here

If you are using python3 use the print function instead.

with open("bob.txt", "w") as myfile:
    print(user1strength, file=myfile)
    print(user1skill, file=myfile)
    print(user2strength, file=myfile)
    print(user2skill, file=myfile)

The print function takes care of converting to str for you, and automatically adds the \\n for you as well. I also used a with block which will automatically close the file for you.

If you are on python2.6 or python2.7, you can get access to the print function with from __future__ import print_function .

One your variables is probably not string type. You can only write strings to a file.

you could do something like this:

# this will make every variable a string
myfile = open ("bob.txt","w")
myfile.write(str(user1strength))
myfile.write("\n")
myfile.write(str(user1skill))
myfile.write("\n")
myfile.write(str(user2strength))
myfile.write("\n")
myfile.write(str(user2skill))
myfile.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM