用Python检查两个文件的新行独立性的方法

2 投票
4 回答
1702 浏览
提问于 2025-04-16 01:30

我试过了

filecmp.cmp(file1,file2)

但是它不管用,因为这两个文件除了换行符以外完全一样。请问在filecmp里有没有这样的选项,或者有没有其他方便的函数/库可以用?还是说我必须逐行读取这两个文件,然后进行比较呢?

4 个回答

0

看起来你只需要检查文件是否相同,忽略空格和换行符。

你可以使用这样的一个函数:

def do_cmp(f1, f2):
    bufsize = 8*1024
    fp1 = open(f1, 'rb')
    fp2 = open(f2, 'rb')
    while True:
        b1 = fp1.read(bufsize)
        b2 = fp2.read(bufsize)
        if not is_same(b1, b2):
            return False
        if not b1:
            return True

def is_same(text1, text2):
    return text1.replace("\n","") == text2.replace("\n","")

你可以改进一下 is_same 函数,让它更符合你的需求,比如说你也可以忽略大小写。

1

可以试试difflib模块,这个模块提供了一些类和函数,用来比较不同的序列。

根据你的需求,difflib.Differ这个类看起来挺有意思的。

class difflib.Differ

这是一个用来比较文本行序列的类,可以生成易于人类理解的差异或变化。Differ使用SequenceMatcher来比较行序列,也可以在相似(几乎匹配的)行中比较字符序列。

可以看看这个示例,它比较了两段文本。被比较的序列也可以通过文件类对象的readlines()方法获取。

5

我觉得像这样的一个简单的便利函数就可以解决问题:

from itertools import izip

def areFilesIdentical(filename1, filename2):
    with open(filename1, "rtU") as a:
        with open(filename2, "rtU") as b:
            # Note that "all" and "izip" are lazy
            # (will stop at the first line that's not identical)
            return all(myprint() and lineA == lineB
                       for lineA, lineB in izip(a.xreadlines(), b.xreadlines()))

撰写回答