python - filecmp 是否进行精确比较?
问题描述
filecmp.cmp
文件状态(强调我的)
比较名为f1和f2
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, f2, 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, f2, s1, 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
所以是的,它会比较文件内容。
推荐阅读
- sql - 如何使用匹配值使用 CSV 文件中的数据更新 Postgres 中的列
- anaconda - Anaconda 安装错误
- javascript - 有没有办法将数据流式传输到一个 blob(或生成一个巨大的 blob)
- ios - 使用键从 2 个 JSON 对象创建单个 JSON 字符串
- windows - SSMS 17.5当单元格数据大于可用显示区域时不显示椭圆
- acumatica - 智能面板中的选择器给出错误'
在系统中找不到。 - c# - 如何使主栏中的页面对除管理员以外的所有人隐藏?
- c# - 从 C# 控制台应用程序打开网页
- php - 如何避免 php 解析整个 php 文件并包含并使其仅解析将使用的内容?
- for-loop - 处理mathematica目录中的大量文件