Search code examples
pythonfileread-write

How to read a file and write it entirely to several text files using Python?


I want to load/read a text file and write it to two other text files "entirely". I will write other different data to the following of these two files later. The problem is that the loaded file is only written to the first file, and no data from that loaded file is written to the second file.

The code I am using:

fin = open("File_Read", 'r')
fout1 = open("File_Write1", 'w')
fout2 = open("File_Write2", 'w')

fout1.write(fin.read())
fout2.write(fin.read())   #Nothing is written here!

fin.close()  
fout1.close()
fout2.close()

What is happening and what is the solution? I prefer using open instead of with open.

Thanks.


Solution

  • Apparently the fin.read() reads all the lines, the next fin.read() will continue from where the previous .read() ended (which is the last line). To solve this, I would simply go for:

    text_fin = fin.read()
    fout1.write(text_fin)
    fout2.write(text_fin)