I having a little trouble to figure out how can I replace the specific lines in a text file by the lines from another text file marching certain pattern. !?!? For example:
I have two files: file1 and file2 , I want to search lines of the first file for specific keywords and then take this lines of the text and replace it in another text file which having a same keywords.

keyword = [word1,word2,wor3,word4]
        file1=open("file1.txt", 'r').read()
        file2=open("file2.txt", 'r+w').read()
        for i in keyword:
                for line in file1:
                    if i in line:
                  # do replace the lines in file2 marching keyword ?
                     '''and here I am stuck.... How  can I search for lines 
                  in second file and then replace this lines by another ones from first file1?'''

Edited by deonis: n/a

7 Years
Discussion Span
Last Post by jice

This should do the trick

f2=open(file2).readlines() # I load the 2d file in a list to be able to change a line by another easily
for l in open(file1): # no need to open the file and read it before. This will read the file line by line
    for k in keywords:
        if k in l:
            for i, l2 in enumerate(f2): # enumerate will give you the number of the line and the line the same time
                if k in l2:
                    f2[i]=l # I change the line
of.writelines(f2) # I rewrite the wole list

Edited by jice: n/a

very nice post! Well explained !

Thank you so much ! It work out of the box in my final program. I did not know we can do that: f2=l.


This is because we loaded the file in a list. This way, we can change whichever line we want (in the list). You can't do that directly in a file.
Then, when everything is ready, we overwrite the file 2 with the content of the list.

Edited by jice: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.