简体   繁体   中英

How to write to multiple files in Python?

I have two files I want to open:

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

Then I want to write to both of them separately:

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

The first write thing is for the first open and the second is for the second. How would I do this?

You are overwriting the file variable with the second open, so all the writes would be directed there. Instead, you should use two variables:

textures_file = open('textures.txt', 'w')
decode_file = open('to_decode.txt', 'w')

textures_file.write("Username: " + username + " Textures: " + textures)
decode_file.write(textures)

Name your file pointers two different things, ie not both "file".

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

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

Right now, the second "file" declaration you're making is over-writing the first one, so file only points to "to_decode.txt".

You can use "with" to avoid mentioning file.close() explicitly. Then You don't have to close it - Python will do it automatically either during garbage collection or at program exit.

with open('textures.txt', 'w') as file1,open('to_decode.txt', 'w') as file2:

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

Just give them different names:

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

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

As others have mentioned, file is the name of a built-in function so using that name for your local variable is a bad choice.

You need to use two different variables, as @Klaus says, to create two different, distinct handles to which you can push operations. So,

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

then

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM