微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

filecmp 是否进行精确比较?

如何解决filecmp 是否进行精确比较?

filecmp.cmp documentation 状态(强调我的)

比较名为f1f2文件,如果它们看起来 相等则返回True,否则返回False
如果 shallow 为真,则具有相同 os.stat() 签名的文件被视为相等。否则,比较文件内容

看起来在这里是什么意思?我的理解是,对于 shallow=False 文件内容进行了比较,因此文件明确要么相同,要么不同。

解决方法

源代码相当简单;在顶部的 filecmp 模块的文档页面中有一个指向它的链接:

def cmp(f1,f2,shallow=True):
    """Compare two files.
    Arguments:
    f1 -- First file name
    f2 -- Second file name
    shallow -- Just check stat signature (do not read the files).
               defaults to True.
    Return value:
    True if the files are the same,False otherwise.
    This function uses a cache for past comparisons and the results,with cache entries invalidated if their stat information
    changes.  The cache may be cleared by calling clear_cache().
    """

    s1 = _sig(os.stat(f1))
    s2 = _sig(os.stat(f2))
    if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG:
        return False
    if shallow and s1 == s2:
        return True
    if s1[1] != s2[1]:
        return False

    outcome = _cache.get((f1,s1,s2))
    if outcome is None:
        outcome = _do_cmp(f1,f2)
        if len(_cache) > 100:      # limit the maximum size of the cache
            clear_cache()
        _cache[f1,s2] = outcome
    return outcome

def _sig(st):
    return (stat.S_IFMT(st.st_mode),st.st_size,st.st_mtime)

def _do_cmp(f1,f2):
    bufsize = BUFSIZE
    with open(f1,'rb') as fp1,open(f2,'rb') as fp2:
        while True:
            b1 = fp1.read(bufsize)
            b2 = fp2.read(bufsize)
            if b1 != b2:
                return False
            if not b1:
                return True

是的,它会比较文件内容。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。