簡體   English   中英

為什么filecmp.cmp不一致?

[英]Why is filecmp.cmp being inconsistent?

這個問題是關於Python 2.7.1中的filecmp模塊的 據我所知,這兩個調用是相同的(Windows,因此大小寫無關緊要)。 一個返回True ,另一個返回False

>>> filecmp.cmp(r'h:\dcim\112_1029\imgp7258.dng', r'd:\pictures\2016\112_1029\imgp7258.dng', False)
True
>>> filecmp.cmp('h:\\dcim\\112_1029\\IMGP7258.DNG', 'd:\\pictures\\2016\\112_1029\\IMGP7258.DNG', False)
False

h:是SD卡,而d:是標准硬盤驅動器。 我已經通過Explorer將文件從h:復制到d: ,所以它們應該是相同的。 為了確保,我什至再次這樣做。 無論我執行多少次或執行的順序如何,每次通話的結果都是一致的。

這里還有一些實驗,只是為了進一步混淆事情。

>>> f1 = r'h:\dcim\112_1029\imgp7258.dng'
>>> f2 = r'd:\pictures\2016\112_1029\imgp7258.dng'
>>> f3 = 'h:\\dcim\\112_1029\\IMGP7258.DNG'
>>> f4 = 'd:\\pictures\\2016\\112_1029\\IMGP7258.DNG'
>>> f1.upper()==f3.upper()
True
>>> f2.upper()==f4.upper()
True
>>> filecmp.cmp(f1, f2, False)
True
>>> filecmp.cmp(f3, f4, False)
False
>>> filecmp.cmp(f1, f4, False)
True
>>> filecmp.cmp(f3, f2, False)
True

根據注釋的要求,這是os.stat的4個文件名中每個文件名的結果。 您可以看到它們除了訪問和創建時間外都是相同的,但是這些時間對於文件名的每個版本都是一致的。

>>> os.stat(f1)
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=15112724L, st_atime=1490418000L, st_mtime=1477766688L, st_ctime=1477766686L)
>>> os.stat(f2)
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=15112724L, st_atime=1490488519L, st_mtime=1477766688L, st_ctime=1490488519L)
>>> os.stat(f3)
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=15112724L, st_atime=1490418000L, st_mtime=1477766688L, st_ctime=1477766686L)
>>> os.stat(f4)
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=15112724L, st_atime=1490488519L, st_mtime=1477766688L, st_ctime=1490488519L)

我想到的另一項測試:

>>> def hashfile(filename):
    m = hashlib.md5()
    with open(filename, 'rb') as f:
        m.update(f.read())
    return ''.join('%02x' % ord(b) for b in m.digest())

>>> hashfile(f1)
'a0042d8623567bcf429069d17e7c3148'
>>> hashfile(f2)
'a0042d8623567bcf429069d17e7c3148'
>>> hashfile(f3)
'a0042d8623567bcf429069d17e7c3148'
>>> hashfile(f4)
'a0042d8623567bcf429069d17e7c3148'
>>> filecmp.cmp(f1, f2, False)
True
>>> filecmp.cmp(f3, f4, False)
False

2.7文檔沒有提及它,但是3.4文檔包含以下非常重要的說明:

此函數將緩存用於過去的比較和結果,如果文件的os.stat()信息發生更改,則緩存條目將無效。 可以使用clear_cache()清除整個緩存。

緩存似乎對文件名區分大小寫。

就我而言,我已經重新復制了文件,因此os.stat()信息沒有改變(Windows保留了這些屬性)。 但是,當我在不同情況下使用文件名進行測試時,得到的未緩存結果與緩存結果不同

按照文檔中的建議調用clear_cache()是解決我的問題的確切方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM