博客
关于我
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进阶语法:字典推导式
查看>>
python gil_Python中GIL的使用详解
查看>>
python glob.glob使用
查看>>
python glob的安装和使用
查看>>
Python google drive API 下载,文件在哪里?
查看>>
Python GPS 模块:读取最新的 GPS 数据
查看>>
python grpc入门
查看>>
python gRPC测试helloworld
查看>>
python gRPC简单示例
查看>>
Python GUI 开发:全面指南
查看>>
Python GUI编程
查看>>
Python hashlib模块
查看>>
python hashlib模块
查看>>
python if,循环的练习
查看>>
Python in open course (week3)
查看>>
Python IO编程
查看>>
Python IO编程详解
查看>>
Python IPL
查看>>
python join split
查看>>
python json文件传输图片
查看>>