-
python入门教程之Python3标准库:filecmp比较文件
本站最新发布 Python从入门到精通|Python基础教程
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
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目录下生成一个文件树。
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',
栏目列表
最新更新
如何使用OS模块中的stat方法
Python os 模块
seek() 方法
python打开文件实例1
Python写入文件
什么是流?
文件操作如何进制逐行读取
Python相对路径
with创建临时运行环境
Python文件操作
.Net Standard(.Net Core)实现获取配置信息
Linux PXE + Kickstart 自动装机
Shell 编程 基础
Shell 编程 条件语句
CentOS8-网卡配置及详解
Linux中LVM逻辑卷管理
1.数码相框-相框框架分析(1)
Ubuntu armhf 版本国内源
Linux中raid磁盘阵列
搭建简易网站
access教程之Access简介
mysql 安装了最新版本8.x版本后的报错:
Mysql空间数据&空间索引(spatial)
如何远程连接SQL Server数据库的图文教程
复制SqlServer数据库的方法
搜索sql语句
sql中返回参数的值
sql中生成查询的模糊匹配字符串
数据定义功能
数据操作功能