博客
关于我
Python 之 filecmp
阅读量:795 次
发布时间:2023-03-06

本文共 4984 字,大约阅读时间需要 16 分钟。

Python filecmp工具详解

filecmp的简单使用

2.1 cmp工具的简单使用

filecmp.cmp(file1, file2)用于比较两个文件是否相同。如果文件相同则返回true,否则返回false。

2.1.1 复制文件并备份

# cp /etc/vnc.conf ./vnc.conf.bak

2.1.2 编写Python代码

#!/usr/bin/env pythonimport sysimport filecmpimport ostry:    file1 = sys.argv[1]    file2 = sys.argv[2]except:    print("Please follow the parameters")    sys.exit()if os.path.isfile(file1) and os.path.isfile(file2):    if filecmp.cmp(file1, file2):        print("Match success")    else:        print("Match failed")else:    print("Please check files")    sys.exit()

2.1.3 执行脚本输出

# python lcmp.py vnc.conf vnc.conf.bak# Match success

执行结果表明文件对比OK。修改vnc.conf.bak内容后再次执行:

# sed -i s/vnc/liwang.org/ vnc.conf.bak# python lcmp.py vnc.conf vnc.conf.bak# Match failed

结果输出"Match failed",表明脚本功能正常。

2.2 cmpfiles工具的简单使用

filecmp.cmpfiles(dir1, dir2, [files...])用于比较两个目录的差异,返回三个列表:匹配文件、不匹配文件、不存在文件。

2.2.1 复制文件到目录

# mkdir -p dir1 dir2# cp lcmp.py vnc.conf vnc.conf.bak dir1/# cp lcmp.py vnc.conf dir2/

2.2.2 编写Python代码

#!/usr/bin/env pythonimport osimport filecmpimport sysdir1 = input("Please enter a folder to match:")dir2 = input("Please enter a folder to match:")files = []while True:    local_files = input("Please enter the file to compare:[n/N Exit the input]")    if local_files in ('N', 'n'):        break    elif local_files == '':        continue    else:        files.append(local_files)try:    os.path.exists(dir1)    os.path.exists(dir2)except:    print("Please check the folder.")    sys.exit()#print(filecmp.cmpfiles(dir1, dir2, files)[0])print("It's file match:", filecmp.cmpfiles(dir1, dir2, files)[0])print("The file does not match:", filecmp.cmpfiles(dir1, dir2, files)[1])print("File does not exists:", filecmp.cmpfiles(dir1, dir2, files)[2])

2.2.3 执行脚本

# python3 lcmpfiles.py# Please enter a folder to match:dir1# Please enter a folder to match:dir2# Please enter the file to compare:[n/N Exit the input]lcmp.py# Please enter the file to compare:[n/N Exit the input]vnc.conf# Please enter the file to compare:[n/N Exit the input]vnc.conf.bak# Please enter the file to compare:[n/N Exit the input]n# It's file match: ['lcmp.py', 'vnc.conf']# The file does not match: []# File does not exists: ['vnc.conf.bak']

2.3 dircmp工具的简单使用

dircmp(a, b, [ignore], [hide])用于递归比较两个目录。提供report()和report_full_closure()方法。

2.3.1 示例环境

# ls dir1/ dir2/# dir1:# hosts  ld.so.conf  sysconfig# dir2:# hosts  ld.so.conf  sysconfig

2.3.2 编写Python代码

#!/usr/bin/env pythonimport filecmpdir1 = "/root/python/d_2_filecmp/cmp/dir1/"dir2 = "/root/python/d_2_filecmp/cmp/dir2/"dirobj = filecmp.dircmp(dir1, dir2)print(dirobj.report())

2.3.3 执行结果

# python simple_filecmp.py# diff /root/python/d_2_filecmp/cmp/dir2 /root/python/d_2_filecmp/cmp/dir1# Identical files : ['ld.so.conf']# Differing files : ['hosts']# Common subdirectories : ['sysconfig']

2.3.4 report_full_closure()方法

#!/usr/bin/env pythonimport filecmpdir1 = "/root/python/d_2_filecmp/cmp/dir1/"dir2 = "/root/python/d_2_filecmp/cmp/dir2/"dirobj = filecmp.dircmp(dir1, dir2)print(dirobj.report_full_closure())

2.3.5 执行结果

# python simple_filecmp_2.py# diff /root/python/d_2_filecmp/cmp/dir1/ /root/python/d_2_filecmp/cmp/dir2/# Identical files : ['ld.so.conf']# Differing files : ['hosts']# Common subdirectories : ['sysconfig']# diff/root/python/d_2_filecmp/cmp/dir1/sysconfig /root/python/d_2_filecmp/cmp/dir2/sysconfig

filecmp案例

3.1 需求

需求:备份etc文件夹下所有内容,并保持实时备份。如果有新文件,copy至备份文件中,如果有修改,update内容。

3.2 流程图

(此处去掉图片链接)

3.3 代码编写

#!/usr/bin/env pythonimport filecmpimport osimport shutilsource_files = "/root/python/d_2_filecmp/dir1"target_files = "/root/python/d_2_filecmp/dir2"def check_common_dirs(source_files, target_files):    dirsobj = filecmp.dircmp(source_files, target_files)    common_dirs_list = dirsobj.common_dirs    for common_line in common_dirs_list:        files_contrast(source_files + '/' + common_line, target_files + '/' + common_line)def files_contrast(dir1, dir2):    dirobj = filecmp.dircmp(dir1, dir2)    no_exists_files = dirobj.left_only    no_diff_files = dirobj.diff_files    for exists_files in no_exists_files:        if os.path.isfile(exists_files):            shutil.copyfile(dir1 + '/' + exists_files, dir2 + '/' + exists_files)        else:            os.makedirs(dir2 + '/' + exists_files)            print("%s is directory" % (exists_files))            try:                files_contrast(dir1 + '/' + exists_files, dir2 + '/' + exists_files)            except:                return    for diff_files in no_diff_files:        if os.path.isfile(diff_files):            os.remove(dir2 + '/' + diff_files)            shutil.copyfile(dir1 + '/' + diff_files, dir2 + '/' + diff_files)        else:            os.makedirs(dir2 + '/' + diff_files)if os.path.exists(source_files):    if not os.path.exists(target_files):        os.makedirs(target_files)    files_contrast(source_files, target_files)    check_common_dirs(source_files, target_files)else:    print("Source files no exists")    sys.exit()

3.4 执行脚本输出

脚本执行后,dir2下会生成与dir1相同的文件结构和内容。

转载地址:http://ebofk.baihongyu.com/

你可能感兴趣的文章
Python Pyinstaller Matplotlibrary
查看>>
Python Pypi 修改 国内源(以豆瓣源为例)
查看>>
Python PyQt5 将不再显示此消息复选框添加到 QMessageBox
查看>>
Python PyQt5:如何使用 PyQt5 显示错误消息
查看>>
Python PYSFTP-以字符串/文本形式传递私钥,而不是传递文件路径
查看>>
Python pytest 面试题!
查看>>
Python pytz 时区函数返回一个相差 9 分钟的时区
查看>>
python rabbitmq实现简单/持久/广播/组播/topic/rpc消息异步发送可配置Django
查看>>
Python random和json模块
查看>>
Python random模块seed理解
查看>>
python range()函数
查看>>
Python rdflib可传递查询
查看>>
Redis 配置高可用和搭建集群
查看>>
python redis 集群_python 搭建redis集群
查看>>
python redis连接,在Python中使用Redis连接池的正确方法
查看>>
python regex_Python RegEx
查看>>
python requests post 中文结果请求得到unicode
查看>>
Python Requests接口自动化测试实战
查看>>
Python requests模块
查看>>
python request与grequests该如何选择
查看>>