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.

JavaScript

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

JavaScript
Advertisement