Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to multiple files in Python?

Tags:

python

file

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?

like image 416
James Anderson Avatar asked Jul 17 '26 17:07

James Anderson


2 Answers

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)
like image 126
Mureinik Avatar answered Jul 19 '26 06:07

Mureinik


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)
like image 35
Ahsanul Haque Avatar answered Jul 19 '26 06:07

Ahsanul Haque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!