![](/img/trans.png)
[英]Read several files and write line n of each file to another file using python
[英]How to read a file and write it entirely to several text files using Python?
我想加载/读取一个文本文件并将其“全部”写入其他两个文本文件。 稍后,我将其他不同的数据写入这两个文件的下面。 问题在于,已加载的文件仅写入第一个文件,而该加载的文件中没有数据写入第二个文件。
我正在使用的代码:
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()
NB 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()
***注意:不是最有效的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.