如何使用 python filecmp 忽略不同的换行符

nic*_*bpe 4 python python-2.7

我有一个比较文件的小脚本

import filecmp
filecmp.cmp(path1, path2)  
Run Code Online (Sandbox Code Playgroud)

True如果文件相似则此代码返回,但False如果换行符不同则返回。path1有 Linux 换行符和path2Windows 换行符。我想知道True文件是否仅与换行符不同。不编辑文件可以吗?

mey*_*er9 5

对于该模块来说这是不可能的,filecmp因为它只能用于stat比较文件并且不会让您覆盖比较。

您可以使用 itertools 做一些事情,如下所示

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, b))
Run Code Online (Sandbox Code Playgroud)