比较 2 个文件夹内的大型 csv 文件,并在 python 中打印确切的差异以及行号

Compare large csv files inside 2 folders and print exact difference along with the line number in python

我必须比较 2 个不同文件夹中的大型 csv 文件。这些文件以相同的名称存储在这些文件夹中。比较后我需要打印文件名、行号和不同的字段。如果其中一个 csv 中缺少任何一行,那么我还需要打印它以及文件名、行号。

我有一个代码可以只打印不同的字段而不是两个给定文件之间的行号。

import csv
import itertools
f1= open("file1.csv")
f2= open("file2.csv")
csv_f1= csv.reader(f1)
csv_f2= csv.reader(f2)
for row1, row2 in zip(csv_f1,csv_f2):
    if row1 != row2:
        print(set(row1)-set(row2))

请帮助将其扩展到文件夹级别并打印文件名和行号以及导致差异的字段。我还需要为缺失的行打印文件名和行号。

我尝试在 csv.reader 部分使用 line_num 函数,但它返回的是其他结果而不是行号。任何查找行号和差异的函数都会有很大帮助。谢谢。

编辑:我按照@Adrian

的要求在下面发布查询和文件
import csv
import itertools
f1= open("D:/Users/KPriya4/Downloads/csv1.csv")
f2= open("D:/Users/KPriya4/Downloads/csv2.csv")
csv_f1= csv.reader(f1)
csv_f2= csv.reader(f2)
line = 0
for row1, row2 in zip(csv_f1,csv_f2):
    if row1 != row2:
        if not row1:
            print("file1.csv: Row " + str(line) + " is empty")
            continue
        if not row2:
            print("file2.csv: Row " + str(line) + " is empty")
            continue
        print(set(row1)-set(row2))
        print(line)
    line += 1

File

File 2 with difference highlighted

文件 1 中名字为 'Carlos' 的第 5 行在文件 2 中丢失。

当我 运行 代码时,我得到以下输出。

enter image description here

这也有另一行(第6行)没有区别。

请原谅我没有发布图片,因为我不允许附加图片,它仅作为链接发布。

根据您提供的新信息,我能够将其整合在一起。您使用的代码的问题在于,由于两个文件的长度不同,当您将它们压缩在一起时,压缩文件的长度将是列表中项目较少的文件之一,因此您会丢失信息。此外,由于没有空白行,您需要遍历另一个列表以检查您要查找的项目是否位于不同的位置。由于您的 CSV 文件包含一个 ID 字段,我认为这将是唯一的,并且我对其进行了迭代:

import csv
import itertools
f1= open("file1.csv")
f2= open("file2.csv")
csv_f1= csv.reader(f1)
csv_f2= csv.reader(f2)

csv_f1 = list(csv_f1)
csv_f2 = list(csv_f2)

line1 = 0
line2 = 0
for row1 in range(0,len(csv_f1)):
    found = False
    # This checks if a row with the same ID exists in the other file and compares them if it does
    for row2 in range(0,len(csv_f2)):
        if csv_f1[row1][1] == csv_f2[row2][1]:
            found = True
            if csv_f1[row1] != csv_f2[row2]:
                print("Line " + str(line1) + " from file 1 and line " + str(line2) + " from file 2 have same ID but different data")
                print(set(csv_f1[row1])-set(csv_f2[row2]))
    if not found:
        print("Line " + str(line1) + " from file 1 is not in file 2")
    line2 += 1
    line1 += 1