如何在Python中向多个文件写入数据?

3

我有两个文件想要打开:

file = open('textures.txt', 'w')
file = open('to_decode.txt', 'w')

然后我想分别向它们写入:

file.write("Username: " + username + " Textures: " + textures)
file.write(textures)

第一次写是为了第一次打开,第二次写是为了第二次。我该怎么做?

1
你尝试过什么吗? - Ahsanul Haque
1
使用两个不同的变量名。同时,file是一个糟糕的选择。它是Python 2中内置函数的名称。 - Klaus D.
file1和file2,或者你可以编写一个函数,在函数中进行打开和写入,这样就不必重复自己了... - Richard
5个回答

3
您正在使用第二个打开操作覆盖了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)

3
您可以使用“with”来避免明确提及file.close()。然后您不必关闭它 - Python会在垃圾回收期间或程序退出时自动关闭它。
with open('textures.txt', 'w') as file1,open('to_decode.txt', 'w') as file2:

    file1.write("Username: " + username + " Textures: " + textures)
    file2.write(textures)

1
然而,with 的主要优点是即使发生错误也会自动关闭文件句柄。 - Markus Meskanen

2

将文件指针命名为两个不同的名称,即不要都命名为“file”。

file1 = open...
file2 = open...

file1.write...
file2.write...

现在,你正在进行第二个“file”声明,它会覆盖第一个声明,因此file仅指向“to_decode.txt”。


0

只需给它们不同的名称:

f1 = open('textures.txt', 'w')
f2 = open('to_decode.txt', 'w')

f1.write("Username: " + username + " Textures: " + textures)
f2.write(textures)

正如其他人所提到的,file是一个内置函数的名称,因此将其用作您的本地变量名称是一个糟糕的选择。


0

你需要使用两个不同的变量,就像@Klaus所说的那样,来创建两个不同的、独立的句柄,以便你可以推送操作。因此,

file1 = open('textures.txt', 'w')
file2 = open('to_decode.txt', 'w')

那么

file1.write("Username: " + username + " Textures: " + textures)
file2.write(textures)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接