我想加载/读取文本文件并将其“完全”写入另外两个文本文件。我稍后会将其他不同的数据写入这两个文件中。问题是加载的文件只写入第一个文件,并且没有来自该加载文件的数据写入第二个文件。
我正在使用的代码:
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而不是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()
注: 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()
***注意:不是最有效的解决方案。