I have multiple files with same name in two directory. How to compare each one with the other line by line ( i.e compare file1 in dir1 with file2 in dir2 line by line if they have same name: So far I have:
dir1 = "dir1"
dir2 = "/dir2"
files1 = os.listdir(dir1)
files2 = os.listdir(dir2)
for x in files2:
for y in files1:
if x == y:
#compare element of each line for e.g in file 1 I have list:
1, 2, 3
2, 4, 6
#file2 I have another list:
2, 4, 3
2, 4, 6
#if first two numbers are equal then output the entire list
CodePudding user response:
Instead of iterating over every file in dir1 against every file in dir2, you can just iterate over the files in dir1 and check if that file exists in dir2 if only interested in the files having the same name.
Then do something like this to compare matching files.
import os
dir1 = "dir1"
dir2 = "dir2"
for file in os.listdir(dir1):
file2 = os.path.join(dir2, file1)
if os.path.exists(file2):
file1 = os.path.join(dir1, file)
print(file)
with open(file1, "r") as f1, open(file2, "r") as f2:
# compare file1 and file2 line by line
# add your logic here to compare the two files
same = True
while True:
line1 = f1.readline()
line2 = f2.readline()
if line1 != line2:
same = False
break
if len(line1) == 0:
break
if same:
print("files are same")
else:
print("files are different")