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

如何在Python中写入多个文件?,python,file,writing,Python,File,Writing,我有两个文件要打开: file = open('textures.txt', 'w') file = open('to_decode.txt', 'w') 然后我想分别给他们两人写信: file.write("Username: " + username + " Textures: " + textures) file.write(textures) 第一个写的东西是第一个打开的,第二个是第二个打开的。 我该如何做到这一点?将文件指针命名为两种不同的名称,即不是同时命名为“文件” 现在,您所

我有两个文件要打开:

file = open('textures.txt', 'w')
file = open('to_decode.txt', 'w')
然后我想分别给他们两人写信:

file.write("Username: " + username + " Textures: " + textures)
file.write(textures)
第一个写的东西是第一个打开的,第二个是第二个打开的。
我该如何做到这一点?

将文件指针命名为两种不同的名称,即不是同时命名为“文件”


现在,您所做的第二个“文件”声明是对第一个声明的重写,因此文件只指向“to_decode.txt”。

只需给它们不同的名称:

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

f1.write("Username: " + username + " Textures: " + textures)
f2.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)

正如@Klaus所说,您需要使用两个不同的变量来创建两个不同的句柄,您可以将操作推送到它们。所以

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

可以使用“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)

你试过什么吗?使用两个不同的变量名。而且
文件
是一个错误的选择。它是Python 2.file1和file2中内置函数的名称,或者您可以编写一个函数,并在函数中执行打开和写入操作,这样您就不必重复自己的操作……然而,
with
的主要优点是,即使发生错误,文件句柄也会自动关闭。
file1.write("Username: " + username + " Textures: " + textures)
file2.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)