我有两个文件想要打开:
file = open('textures.txt', 'w')
file = open('to_decode.txt', 'w')
然后我想分别向它们写入:
file.write("Username: " + username + " Textures: " + textures)
file.write(textures)
第一次写是为了第一次打开,第二次写是为了第二次。我该怎么做?
file
变量,因此所有写入都会被导向到该位置。相反,您应该使用两个变量:textures_file = open('textures.txt', 'w')
decode_file = open('to_decode.txt', 'w')
textures_file.write("Username: " + username + " Textures: " + textures)
decode_file.write(textures)
with open('textures.txt', 'w') as file1,open('to_decode.txt', 'w') as file2:
file1.write("Username: " + username + " Textures: " + textures)
file2.write(textures)
with
的主要优点是即使发生错误也会自动关闭文件句柄。 - Markus Meskanen将文件指针命名为两个不同的名称,即不要都命名为“file”。
file1 = open...
file2 = open...
file1.write...
file2.write...
现在,你正在进行第二个“file”声明,它会覆盖第一个声明,因此file仅指向“to_decode.txt”。
只需给它们不同的名称:
f1 = open('textures.txt', 'w')
f2 = open('to_decode.txt', 'w')
f1.write("Username: " + username + " Textures: " + textures)
f2.write(textures)
正如其他人所提到的,file是一个内置函数的名称,因此将其用作您的本地变量名称是一个糟糕的选择。
你需要使用两个不同的变量,就像@Klaus所说的那样,来创建两个不同的、独立的句柄,以便你可以推送操作。因此,
file1 = open('textures.txt', 'w')
file2 = open('to_decode.txt', 'w')
那么
file1.write("Username: " + username + " Textures: " + textures)
file2.write(textures)
file
是一个糟糕的选择。它是Python 2中内置函数的名称。 - Klaus D.