在python中写入和读取文件的问题

2024-07-04 17:33:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在一个文本文件中写入和读取多个变量

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


Tags: txtmostclose错误openmyfilewritebob
3条回答

变量之一可能不是字符串类型。只能将字符串写入文件。你知道吗

你可以这样做:

# 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()

如果您使用的是python3,请改用print函数。你知道吗

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

print函数负责为您转换成str,并自动为您添加\n。我还使用了with块,它将自动为您关闭文件。你知道吗

如果您使用的是python2.6或python2.7,则可以使用from __future__ import print_function访问print函数。你知道吗

write接受字符串。所以你可以构造一个字符串然后一次传递它。你知道吗

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

另外,如果您的python支持with,您可以这样做:

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

# code continues, file is closed properly here

相关问题 更多 >

    热门问题