Skip to content
Advertisement

Comparing two text files and the matches go to a new file

In python I would like to find a way to compare two text files and read one line by line and find it’s match if any in the other file. If they match I would like to take that string and write it to a new file.

I do not know how I would even start this the only thing I know how to do is how to read a text file but not compare it to another.

Any starting tips, links, or ideas would be great.

Thank you

Advertisement

Answer

Try something like this.

with open('file1.txt') as file1:
     with open('file2.txt') as file2:
           newfile = open('newfile.txt','w')
           for range(len(file1.readlines())):
                s1 = file1.readline()
                s2 = file2.readline()
                if s1 == s2:
                       newfile.write(s1)
           newfile.close()     
   

Or something simpler like @SUTerliakov pointed out common_lines = set(file1.readlines()) & set(file2.readlines()) instead of the checking block such as:

with open('file1.txt') as file1:
     with open('file2.txt') as file2:
           newfile = open('newfile.txt','w')
           common_lines = set(file1.readlines()) & set(file2.readlines())
           for line in common_lines:
                 newfile.write(line)

            newfile.close() 
Advertisement