简体   繁体   中英

How to replace specified lines from file1 with lines from file2 in python

I have two files... file1 and 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.

Eg (file2)

26.78883
25.09446
26.23765
etc.

So in file1 i have "$$$" throughout the file, not just once. How can i replace each "$$$" with a line from file2? The first line in file2 would replace the first "$$$" and then the second file2 line replaces the second "$$$" in file1 and so on...

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM