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 6 Years Ago by deonis: n/a

This should do the trick

keywords=[word1,word2,wor3,word4]
file1="/path/to/file1.txt"
file2="/path/to/file2.txt"
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=open(file2,"w")
of.writelines(f2) # I rewrite the wole list
of.close()

Edited 6 Years Ago by jice: n/a

Comments
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 6 Years Ago by jice: n/a

This article has been dead for over six months. Start a new discussion instead.