Python3 filecmp模块测试比较文件原理解析


Posted in Python onMarch 23, 2020

1.filecmp比较文件

filecmp模块提供了一些函数和一个类来比较文件系统上的文件和目录。

1.1 示例数据

使用下面代码创建一组测试文件。

import os
def mkfile(filename, body=None):
  with open(filename, 'w') as f:
    f.write(body or filename)
  return
 
def make_example_dir(top):
  if not os.path.exists(top):
    os.mkdir(top)
  curdir = os.getcwd()
  os.chdir(top)
  os.mkdir('dir1')
  os.mkdir('dir2')
  mkfile('dir1/file_only_in_dir1')
  mkfile('dir2/file_only_in_dir2')
  os.mkdir('dir1/dir_only_in_dir1')
  os.mkdir('dir2/dir_only_in_dir2')
  os.mkdir('dir1/common_dir')
  os.mkdir('dir2/common_dir')
  mkfile('dir1/common_file', 'this file is the same')
  os.link('dir1/common_file', 'dir2/common_file')
  mkfile('dir1/contents_differ')
  mkfile('dir2/contents_differ')
  # Update the access and modification times so most of the stat
  # results will match.
  st = os.stat('dir1/contents_differ')
  os.utime('dir2/contents_differ', (st.st_atime, st.st_mtime))
  mkfile('dir1/file_in_dir1', 'This is a file in dir1')
  os.mkdir('dir2/file_in_dir1')
  os.chdir(curdir)
  return
 
if __name__ == '__main__':
  os.chdir(os.path.dirname(__file__) or os.getcwd())
  make_example_dir('example')
  make_example_dir('example/dir1/common_dir')
  make_example_dir('example/dir2/common_dir')

运行这个脚本会在axample目录下生成一个文件树。

Python3 filecmp模块测试比较文件原理解析

common_dir目录下也有同样的目录结构,以提供有意思的递归比较选择。

1.2 比较文件

cmp()用于比较文件系统上的两个文件。

import filecmp
print('common_file  :', end=' ')
print(filecmp.cmp('example/dir1/common_file',
         'example/dir2/common_file',
         shallow=True),
   end=' ')
print(filecmp.cmp('example/dir1/common_file',
         'example/dir2/common_file',
         shallow=False))
print('contents_differ:', end=' ')
print(filecmp.cmp('example/dir1/contents_differ',
         'example/dir2/contents_differ',
         shallow=True),
   end=' ')
print(filecmp.cmp('example/dir1/contents_differ',
         'example/dir2/contents_differ',
         shallow=False))
print('identical   :', end=' ')
print(filecmp.cmp('example/dir1/file_only_in_dir1',
         'example/dir1/file_only_in_dir1',
         shallow=True),
   end=' ')
print(filecmp.cmp('example/dir1/file_only_in_dir1',
         'example/dir1/file_only_in_dir1',
         shallow=False))

shallo参数告诉cmp()除了文件的元数据外,是否还要查看文件的内容。默认情况下,会使用由os.stat()得到的信息来完成一个浅比较。如果结果是一样的,则认为文件相同。因此,对于同时创建的相同大小的文件,即使他们的内容不同,也会报告为是相同的文件。当shallow为False时,则要比较文件的内容。

Python3 filecmp模块测试比较文件原理解析

如果非递归的比较两个目录中的一组文件,则可以使用cmpfiles()。参数是目录名和两个位置上要检查的我就爱你列表。传入的公共文件列表应当只包含文件名(目录会导致匹配不成功),而且这些文件在两个位置上都应当出现。下一个例子显示了构造公共列表的一种简单方法。与cmp()一样,这个比较也有一个shallow标志。

import filecmp
import os
# Determine the items that exist in both directories
d1_contents = set(os.listdir('example/dir1'))
d2_contents = set(os.listdir('example/dir2'))
common = list(d1_contents & d2_contents)
common_files = [
  f
  for f in common
  if os.path.isfile(os.path.join('example/dir1', f))
]
print('Common files:', common_files)
# Compare the directories
match, mismatch, errors = filecmp.cmpfiles(
  'example/dir1',
  'example/dir2',
  common_files,
)
print('Match    :', match)
print('Mismatch  :', mismatch)
print('Errors   :', errors)

cmpfiles()返回3个文件名列表,分别包含匹配的文件、不匹配的文件和不能比较的文件(由于权限问题或出于其他原因)。

Python3 filecmp模块测试比较文件原理解析

1.3 比较目录

前面介绍的函数适合完成相对简单的比较。对于大目录树的递归比较或者更完整的分析,dircmp类很更有用。在最简单的用例中,report()会打印比较两个目录的报告。

import filecmp
dc = filecmp.dircmp('example/dir1', 'example/dir2')
dc.report()

输出是一个纯文本报告,显示的结果只包括给定目录的内容,而不会递归比较其子目录。在这里,认为文件not_the_same是相同的,因为这里没有比较内容。无法让dircmp像cmp()那样比较文件的内容。

Python3 filecmp模块测试比较文件原理解析

为了更多的细节,也为了完成一个递归比较,可以使用report_full_closure()。

import filecmp
dc = filecmp.dircmp('example/dir1', 'example/dir2')
dc.report_full_closure()

输出将包括所有同级子目录的比较。

Python3 filecmp模块测试比较文件原理解析

1.4 在程序中使用差异

除了生成打印报告,dircmp还能计算文件列表,可以在程序中直接使用。以下各个属性只在请求时才计算,所以对于未用的数据,创建dircmp实例不会带来开销。

import filecmp
import pprint
dc = filecmp.dircmp('example/dir1', 'example/dir2')
print('Left:')
pprint.pprint(dc.left_list)
print('\nRight:')
pprint.pprint(dc.right_list)

所比较目录中包含的文件和子目录分别列在left_list和right_list中。

Python3 filecmp模块测试比较文件原理解析

可以向构造函数传入一个要忽略的名字列表(该列表中指定的名字将被忽略)来对输入进行过滤。默认的,RCS、CVS和tags等名字会被忽略。

import filecmp
import pprint
dc = filecmp.dircmp('example/dir1', 'example/dir2',
          ignore=['common_file'])
print('Left:')
pprint.pprint(dc.left_list)
print('\nRight:')
pprint.pprint(dc.right_list)

在这里,将common_file从要比较的文件列表中去除。

Python3 filecmp模块测试比较文件原理解析

两个输入目录中共有的文件名会保存在common内,各目录独有的文件会列在left_only和right_only中。

import filecmp
import pprint
dc = filecmp.dircmp('example/dir1', 'example/dir2')
print('Common:')
pprint.pprint(dc.common)
print('\nLeft:')
pprint.pprint(dc.left_only)
print('\nRight:')
pprint.pprint(dc.right_only)

"左"目录是dircmp()的第一个参数,"右"目录是第二个参数。

Python3 filecmp模块测试比较文件原理解析

公共成员可以被进一步分解为文件、目录和“有趣”元素(两个目录中类型不同的内容,或者os.stat()指出的有错误的地方)。

import filecmp
import pprint
dc = filecmp.dircmp('example/dir1', 'example/dir2')
print('Common:')
pprint.pprint(dc.common)
print('\nDirectories:')
pprint.pprint(dc.common_dirs)
print('\nFiles:')
pprint.pprint(dc.common_files)
print('\nFunny:')
pprint.pprint(dc.common_funny)

在示例数据中,file_in_dir1元素在一个目录中是一个文件,而在另一个目录中是一个子目录,所以它会出现在“有趣”列表中。

Python3 filecmp模块测试比较文件原理解析

文件之间的差别也可以做类似的划分。

import filecmp
dc = filecmp.dircmp('example/dir1', 'example/dir2')
print('Same   :', dc.same_files)
print('Different :', dc.diff_files)
print('Funny   :', dc.funny_files)

文件not_the_same通过os.stat()比较,并且不检查内容,所以它包含在same_files列表中。

Python3 filecmp模块测试比较文件原理解析

最后一点,子目录也会被保存,以便容易地完成递归比较。

import filecmp
dc = filecmp.dircmp('example/dir1', 'example/dir2')
print('Subdirectories:')
print(dc.subdirs)

属性subdirs是一个字典,它将目录名映射到新的dircmp对象。

Python3 filecmp模块测试比较文件原理解析

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python 获取新浪微博的最新公共微博实例分享
Jul 03 Python
Django中传递参数到URLconf的视图函数中的方法
Jul 18 Python
举例讲解Python设计模式编程中对抽象工厂模式的运用
Mar 02 Python
Linux上安装Python的PIL和Pillow库处理图片的实例教程
Jun 23 Python
Python中pow()和math.pow()函数用法示例
Feb 11 Python
Python KMeans聚类问题分析
Feb 23 Python
使用python进行文本预处理和提取特征的实例
Jun 05 Python
解决python中 f.write写入中文出错的问题
Oct 31 Python
python基于TCP实现的文件下载器功能案例
Dec 10 Python
解决pymysql cursor.fetchall() 获取不到数据的问题
May 15 Python
Ubuntu配置Pytorch on Graph (PoG)环境过程图解
Nov 19 Python
python使用pywinauto驱动微信客户端实现公众号爬虫
May 19 Python
python实现遍历文件夹图片并重命名
Mar 23 #Python
Python3 mmap内存映射文件示例解析
Mar 23 #Python
Python3 io文本及原始流I/O工具用法详解
Mar 23 #Python
python实现横向拼接图片
Mar 23 #Python
Python操作Excel工作簿的示例代码(\*.xlsx)
Mar 23 #Python
python实现拼接图片
Mar 23 #Python
python使用PIL剪切和拼接图片
Mar 23 #Python
You might like
10条PHP高级技巧[修正版]
2011/08/02 PHP
PHP过滤器 filter_has_var() 函数用法实例分析
2020/04/23 PHP
js活用事件触发对象动作
2008/08/10 Javascript
风吟的小型JavaScirpt库 (FY.JS).
2010/03/09 Javascript
jquery异步调用页面后台方法‏(asp.net)
2011/03/01 Javascript
JS中的prototype与面向对象的实例讲解
2013/05/22 Javascript
JavaScript 作用域链解析
2014/11/13 Javascript
jQuery中detach()方法用法实例
2014/12/25 Javascript
JS模拟键盘打字效果的方法
2015/08/05 Javascript
angular route中使用resolve在uglify压缩后问题解决
2016/09/21 Javascript
纯js模仿windows系统日历
2017/02/04 Javascript
基于AngularJS实现的工资计算器实例
2017/06/16 Javascript
微信小程序button组件使用详解
2018/01/31 Javascript
深入了解javascript 数组的sort方法
2018/06/01 Javascript
Node.js assert断言原理与用法分析
2019/01/04 Javascript
JavaScript算法学习之冒泡排序和选择排序
2019/11/02 Javascript
VUEX-action可以修改state吗
2019/11/19 Javascript
TypeScript魔法堂之枚举的超实用手册
2020/10/29 Javascript
python 简易计算器程序,代码就几行
2009/08/29 Python
跟老齐学Python之大话题小函数(2)
2014/10/10 Python
理解Python中的类与实例
2015/04/27 Python
python嵌套函数使用外部函数变量的方法(Python2和Python3)
2016/01/31 Python
Python中实现最小二乘法思路及实现代码
2018/01/04 Python
Django 忘记管理员或忘记管理员密码 重设登录密码的方法
2018/05/30 Python
python 默认参数相关知识详解
2019/09/18 Python
Python3.9新特性详解
2020/10/10 Python
Python中全局变量和局部变量的理解与区别
2021/02/07 Python
GLAMGLOW香港官网:明星出镜前的秘密武器
2017/03/16 全球购物
自1926年以来就为冰岛保持温暖:66°North
2020/11/27 全球购物
小小商店教学反思
2014/04/27 职场文书
三八红旗手先进事迹材料
2014/05/13 职场文书
调研汇报材料范文
2014/08/17 职场文书
党的群众路线教育实践活动个人对照检查材料(教师)
2014/11/04 职场文书
2014年世界艾滋病日宣传活动总结
2014/11/18 职场文书
Python-typing: 类型标注与支持 Any类型详解
2021/05/10 Python
浅谈mysql执行过程以及顺序
2021/05/12 MySQL