如何使用 Python 读取一个文件并将其完全写入多个文本文件?

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

我想 load/read 一个文本文件并将其写入另外两个文本文件 "entirely"。稍后我会在这两个文件的后面写入其他不同的数据。 问题是加载的文件只写入了第一个文件,而加载文件中的数据没有写入第二个文件。

我使用的代码:

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()

这是怎么回事,解决办法是什么? 我更喜欢使用 open 而不是 with open.

谢谢。

显然 fin.read() 读取所有行,下一个 fin.read() 将从前一个 .read() 结束的地方(即最后一行)继续。为了解决这个问题,我会简单地去:

text_fin = fin.read()
fout1.write(text_fin)
fout2.write(text_fin)
fin = open("test.txt", 'r')
data = fin.read()
fin.close()  

fout1 = open("test2.txt", 'w')
fout1.write(data)
fout1.close()

fout2 = open("test3.txt", 'w')
fout2.write(data)
fout2.close()

N.B。 with open 是最安全和最好的方法,但至少您需要在不再需要时立即关闭文件。

您可以尝试逐行遍历原始文件并将其附加到两个文件。你 运行 陷入了这个问题,因为 file.write() 方法接受字符串参数。

fin = open("File_Read",'r')
fout1 = open("File_Write1",'a')   #append permissions for line-by-line writing
fout2 = open("File_Write2",'a')   #append permissions for line-by-line writing
for lines in fin:
    fout1.write(lines)
    fout2.write(lines)

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

*** 注意:这不是最有效的解决方案。