簡體   English   中英

如何用python中的file2中的行替換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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM