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

时间:2013-11-26 17:37:02

标签: python file text

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

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> {
{1}}
myfile.write(user1strength)

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

如果您使用的是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)

打印功能负责为您转换为str,并自动为您添加\n。我还使用了一个with块,它会自动为你关闭文件。

如果您使用的是python2.6或python2.7,则可以使用from __future__ import print_function访问打印功能。

答案 2 :(得分:0)

你的一个变量可能不是字符串类型。您只能将字符串写入文件。

你可以这样做:

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