[英]How to replace specified lines from file1 with lines from file2 in python
I have two files... file1 and file2.我有两个文件...file1 和file2。 file1 is A LOT of text (no real structure) and file2 is made up of longitude points, each point is on a new line. file1 是很多文本(没有真正的结构),file2 由经度点组成,每个点都在一个新行上。
Eg (file2)例如(文件 2)
26.78883
25.09446
26.23765
etc.
So in file1 i have "$$$" throughout the file, not just once.所以在file1中,我在整个文件中都有“$$$”,而不仅仅是一次。 How can i replace each "$$$" with a line from file2?如何用 file2 中的一行替换每个“$$$”? The first line in file2 would replace the first "$$$" and then the second file2 line replaces the second "$$$" in file1 and so on... file2 中的第一行将替换第一个 "$$$",然后第二个 file2 行替换 file1 中的第二个 "$$$",依此类推...
I am a complete noob and have been struggling with this for a while.我是一个完整的菜鸟,并且已经为此苦苦挣扎了一段时间。 Any help is greatlly appreciated!非常感谢任何帮助!
You could try something like this:你可以尝试这样的事情:
#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.