我在兩個目錄中有多個同名檔案。如何逐行比較每一個與另一個(即,如果它們具有相同的名稱,則將 dir1 中的 file1 與 dir2 中的 file2 逐行比較:到目前為止,我有:
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
uj5u.com熱心網友回復:
無需針對dir2中的每個檔案遍歷dir1中的每個檔案,您只需遍歷dir1 中的檔案,并檢查該檔案是否存在于dir2 中(如果只對具有相同名稱的檔案感興趣)。
然后做這樣的事情來比較匹配的檔案。
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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/347437.html
