[英]Copy N lines from File1 to File2, then delete copied lines in File1
[英]How to replace specified lines from file1 with lines from file2 in python
我有两个文件...file1 和file2。 file1 是很多文本(没有真正的结构),file2 由经度点组成,每个点都在一个新行上。
例如(文件 2)
26.78883
25.09446
26.23765
etc.
所以在file1中,我在整个文件中都有“$$$”,而不仅仅是一次。 如何用 file2 中的一行替换每个“$$$”? file2 中的第一行将替换第一个 "$$$",然后第二个 file2 行替换 file1 中的第二个 "$$$",依此类推...
我是一个完整的菜鸟,并且已经为此苦苦挣扎了一段时间。 非常感谢任何帮助!
你可以尝试这样的事情:
#read the first file to a string
with open("file1.txt") as f:
text = f.read()
#read the second file to a list
with open("file2.txt") as f:
longitudes = f.read().split("\n")
#replace each '$$$' with values from longitudes
while len(longitudes)>0 or "$$$" in text:
text = text.replace("$$$", longitudes.pop(0), 1)
#write to a new file
with open("output.txt", "w") as f:
f.write(text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.