Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you

>Solution :

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() 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading