0

[使用Python3]我想比较两个csv文件的内容,如果内容相同就让脚本打印。换句话说,它应该让我知道是否所有行都匹配,如果不匹配,则不匹配的行数。

此外,我希望以后可以灵活地更改代码以将所有与另一个文件不匹配的行写入。

此外,虽然这两个文件在技术上应该包含完全相同的内容,但行的顺序可能不同(第一行除外,它包含标题)。

输入文件如下所示:

field1  field2  field3  field4  ...
string  float   float   string  ...
string  float   float   string  ...
string  float   float   string  ...
string  float   float   string  ...
string  float   float   string  ...
...     ...     ...     ...     ...

我目前正在运行的代码如下(如下),但老实说,我不确定这是否是最好的(最 Python 的)方式。另外我不确定try: while 1: ...代码在做什么。这段代码是我搜索论坛和 python 文档的结果。到目前为止,代码运行了很长时间。

由于我是新手,我非常渴望收到有关代码的任何反馈,并且还希望对您可能提出的任何建议进行解释。

代码:

import csv
import difflib

'''
Checks the content of two csv files and returns a message.
If there is a mismatch, it will output the number of mismatches.
'''

def compare(f1, f2):

    file1 = open(f1).readlines()
    file2 = open(f2).readlines()

    diff = difflib.ndiff(file1, file2)

    count = 0

    try:
        while 1:
            count += 1
            next(diff)
    except:
        pass

    return 'Checked {} rows and found {} mismatches'.format(len(file1), count)

print (compare('outfile.csv', 'test2.csv'))

编辑: 该文件可以包含重复项,因此存储在一个集合中将不起作用(因为它会删除所有重复项,对吗?)。

4

2 回答 2

2

try-while 块只是简单地迭代diff,你应该使用 for 循环来代替:

count = 0
for delta in diff:
    count += 1

或者更 Pythonic 的生成器表达式

count = sum(1 for delta in diff)

(原始代码count在每次迭代之前都会递增,因此计数会增加一。我想知道在您的情况下这是否正确。)

于 2013-06-18T12:48:06.527 回答
0

To answer your question about while 1:

Please read more about Generators and iterators.

Diff.ndiff() is a generator, which returns and iterator. The loop is iterating over it by calling next(). As long as it finds the diff (iterator moves next) it increments the count (which gives you the total number of rows that differ)

于 2013-06-18T13:11:29.113 回答