我需要在一个文本文件中写入和读取多个变量
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()
现在出现了这样一个错误:
Traceback (most recent call last):
File "D:\python\project2\project2.py", line 70, in <module>
myfile.write(user1strength)
TypeError: must be str, not float
变量之一可能不是字符串类型。只能将字符串写入文件。你知道吗
你可以这样做:
如果您使用的是python3,请改用print函数。你知道吗
print函数负责为您转换成
str
,并自动为您添加\n
。我还使用了with
块,它将自动为您关闭文件。你知道吗如果您使用的是python2.6或python2.7,则可以使用
from __future__ import print_function
访问print函数。你知道吗write
接受字符串。所以你可以构造一个字符串然后一次传递它。你知道吗另外,如果您的python支持
with
,您可以这样做:相关问题 更多 >
编程相关推荐