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
x
11
11
1
with open('file1.txt') as file1:
2
with open('file2.txt') as file2:
3
newfile = open('newfile.txt','w')
4
for range(len(file1.readlines())):
5
s1 = file1.readline()
6
s2 = file2.readline()
7
if s1 == s2:
8
newfile.write(s1)
9
newfile.close()
10
11
Or something simpler like @SUTerliakov pointed out
common_lines = set(file1.readlines()) & set(file2.readlines())
instead of the checking block such as:
JavaScript
1
9
1
with open('file1.txt') as file1:
2
with open('file2.txt') as file2:
3
newfile = open('newfile.txt','w')
4
common_lines = set(file1.readlines()) & set(file2.readlines())
5
for line in common_lines:
6
newfile.write(line)
7
8
newfile.close()
9