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

时间:2015-09-12 14:29:55

标签: python file writing

我想要打开两个文件:

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

然后我想分别写两个:

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

第一个写东西是第一个打开,第二个是第二个。 我该怎么做?

5 个答案:

答案 0 :(得分: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)

答案 1 :(得分:2)

将文件指针命名为两个不同的东西,即不是" file"。

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

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

现在,第二个"文件"您正在制作的声明覆盖了第一个,因此文件只指向" to_decode.txt"。

答案 2 :(得分:0)

给他们不同的名字:

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

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

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

答案 3 :(得分:0)

你需要使用两个不同的变量,如@Klaus所说,创建两个不同的,不同的句柄,你可以推动操作。所以,

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

然后

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

答案 4 :(得分:0)

您可以使用""避免明确提及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)