Fed*_*oni 64
低级方式:
from __future__ import with_statement
with open(filename1) as f1:
with open(filename2) as f2:
if f1.read() == f2.read():
...
Run Code Online (Sandbox Code Playgroud)
高层次的方式:
import filecmp
if filecmp.cmp(filename1, filename2, shallow=False):
...
Run Code Online (Sandbox Code Playgroud)
Ric*_*ich 24
如果你想提高基本效率,你可能想先检查文件大小:
if os.path.getsize(filename1) == os.path.getsize(filename2):
if open('filename1','r').read() == open('filename2','r').read():
# Files are the same.
Run Code Online (Sandbox Code Playgroud)
这样可以节省您读取两个文件大小相同的每一行,因此不能相同.
(更进一步,你可以调用每个文件的快速MD5sum并比较它们,但这不是"在Python中",所以我会在这里停止.)
tzo*_*zot 10
这是一个功能风格的文件比较功能.如果文件大小不同,它立即返回False; 否则,它读入4KiB块大小并在第一个差异时立即返回False:
from __future__ import with_statement
import os
import itertools, functools, operator
def filecmp(filename1, filename2):
"Do the two files have exactly the same contents?"
with open(filename1, "rb") as fp1, open(filename2, "rb") as fp2:
if os.fstat(fp1.fileno()).st_size != os.fstat(fp2.fileno()).st_size:
return False # different sizes ? not equal
fp1_reader= functools.partial(fp1.read, 4096)
fp2_reader= functools.partial(fp2.read, 4096)
cmp_pairs= itertools.izip(iter(fp1_reader, ''), iter(fp2_reader, ''))
inequalities= itertools.starmap(operator.ne, cmp_pairs)
return not any(inequalities)
if __name__ == "__main__":
import sys
print filecmp(sys.argv[1], sys.argv[2])
Run Code Online (Sandbox Code Playgroud)
只是一个不同的采取:)
小智 6
由于我不能评论别人的答案,我会写自己的.
如果你使用md5,你肯定不能只是md5.update(f.read()),因为你会使用太多的内存.
def get_file_md5(f, chunk_size=8192):
h = hashlib.md5()
while True:
chunk = f.read(chunk_size)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
Run Code Online (Sandbox Code Playgroud)