如何在Python中比较文件
问题。
您需要在 Python 中比较文件。
解决方案..
python中的filecmp模块可以用来比较文件和目录。 1.
cmp(文件1, 文件2[, 浅])
filecmp 比较文件 file1 和 file2,如果相同则返回 True,否则返回 False。默认情况下,具有与 os.stat() 返回的相同属性的文件被认为是相等的。如果没有提供shallow(或者为True),则具有相同stat签名的文件被认为是相等的
cmpfiles ( dir1 , dir2 , 通用 [ , 浅 ] )
列表中包含的文件内容在两个目录dir1和dir2中是共同的cmpfiles 返回一个包含三个列表的元组 - 匹配、不匹配、错误
match - 列出两个目录中相同的文件。
不匹配 - 列出不匹配的文件。
错误 - 列出由于某种原因无法比较的文件。
dircmp(dir1, dir2[,忽略[,隐藏]])
创建一个目录比较对象,可用于对目录dir1和dir2执行各种比较操作。
ignore - 忽略要忽略的文件名列表,默认值为 ["RCS"、"CVS"、"tags"]。 p>
hide - 要隐藏的文件名列表,UNIX 上的默认列表为 [OS.curdir, os.pardir](['.', '..'] .
filecmp.dircmp 的实例实现以下方法,将详细报告打印到 sys.stdout:
report():打印两个目录之间的比较。
report_partial_closure() :打印两个目录以及两个
目录的直接子目录的比较。report_full_closure() :打印两个目录、它们的所有子目录、这些子目录的所有子目录等的比较(即递归地)。
left_list:在目录path1中找到的文件和子目录,不包括hidelist的元素。
right_list:在目录path2中找到的文件和子目录,不包括hidelist的元素。
common:目录path1和目录path2中的文件和子目录。
left_only:仅位于目录 path1 中的文件和子目录。
right_only:仅位于目录 path2 中的文件和子目录。
common_dirs:目录path1和目录path2中的子目录。
common_files:目录path1和目录path2中的文件。
same_files:目录path1和目录path2中内容相同的文件的路径。
diff_files:目录path1和目录path2中但内容不同的文件的路径。
funny_files:同时位于目录 path1 和目录 path2 中但由于某种原因无法进行比较的文件的路径。
subdirs:将 common_dirs 中的名称映射到 dircmp 对象的字典。
准备测试数据进行比较
import os
# 准备测试数据
def makefile(filename,text=None):
"""
Function: make some files
params : input file, body
"""
with open(filename, 'w') as f:
f.write(text or filename)
return
# 准备测试数据
def makedirectory(目录名):
"""
功能:建立目录
参数:输入目录
"""
如果 os .path 不存在(directory_name):
os.mkdir(目录名)
# 获取当前工作目录
当前目录 = os.getcwd()
# 更改到提供的目录
os.chdir(目录名)
# 建立两个目录
os.mkdir("dir1")
os.mkdir("dir2")
# 建立两个相同的子目录
os.mkdir("dir1/common_dir")
os.mkdir("dir2/common_dir")
# 创建两个不同的子目录
os.mkdir("dir1/dir_only_in_dir1")
os.mkdir("dir2/dir_only_in_dir2")
# 在目录下各创建一个唯一的文件
makefile("dir1/file_only_in_dir1")
makefile("dir2/file_only_in_dir2")
# 在目录下各创建一个唯一的文件
makefile("dir1/common_file","你好,编写相同的内容")
makefile("dir2/common_file","你好,编写相同的内容")
# 在目录中创建一个非唯一文件
makefile("dir1/not_the_same")
makefile("dir2/not_the_same")
makefile('dir1/file_in_dir1','这是 dir1 中的文件')
os.mkdir('dir2/file_in_dir1')
os.chdir(present_directory)
return
if __name__ == '__main__':
os.chdir(os.getcwd())
makedirectory('example')
makedirectory('example/dir1/common_dir')
makedirectory('example/dir2/common_dir')
filecmp 示例 运行 filecmp 示例。浅层参数告诉 cmp() 除了元数据之外是否查看文件的内容。
默认情况是使用 os.stat() 中提供的信息执行浅层比较。如果结果相同,则认为文件相同。因此,同时创建的相同大小的文件将被报告为相同,即使它们的内容不同。
当shallow为False时,总是比较文件的内容。
import filecmp
print('Output \n *** Common File :', end=' ')
print(filecmp.cmp('example/dir1/common_file',
'example/dir2/common_file'), end=' ')
print(filecmp.cmp('example/dir1/common_file',
'example/dir2/common_file', shallow=False))
print(' *** Different Files :', end=' ')
print(filecmp.cmp('example/dir1/not_the_same',
'example/dir2/not_the_same'), end=' ')
print(filecmp.cmp('example/dir1/not_the_same',
'example/dir2/not_the_same', shallow=False))
print(' *** Identical Files :', end=' ')
print(filecmp.cmp('example/dir1/file_only_in_dir1',
'example/dir1/file_only_in_dir1'), end=' ')
print(filecmp.cmp('example/dir1/file_only_in_dir1',
'example/dir1/file_only_in_dir1', shallow=False))
输出
*** Common File : True True *** Different Files : False False *** Identical Files : True True
cmp 文件示例:
使用 cmpfiles() 比较两个目录中的一组文件,无需递归。
import filecmp
import os
# 确定两个目录中都存在的项目。
dir1_contents = set(os.listdir('example/dir1'))
dir2_contents = set(os.listdir('example/dir2'))
common = list(dir1_contents & dir2_contents)
common_files = [f for f in common if os.path.isfile(os.path.join('example/dir1', f))]
print(f' *** Common files are : {common_files}')
# 现在,让我们比较一下目录
match, mismatch, errors = filecmp.cmpfiles(
'example/dir1',
'example/dir2',
common_files,)
print(f' *** Matched files are : {match}')
print(f' *** mismatch files are : {mismatch}')
print(f' *** errors files are : {errors}')
*** Common files are : ['file_in_dir1', 'not_the_same', 'common_file'] *** Matched files are : ['common_file'] *** mismatch files are : ['file_in_dir1', 'not_the_same'] *** errors files are : []
7.比较目录。
import filecmp
dc = filecmp.dircmp('example/dir1', 'example/dir2')
print(f"output \n *** Printing detaile report: \n ")
print(dc.report())
print(f"\n")
print(dc.report_full_closure())
输出
*** Printing detaile report: diff example/dir1 example/dir2 Only in example/dir1 : ['dir_only_in_dir1', 'file_only_in_dir1'] Only in example/dir2 : ['dir_only_in_dir2', 'file_only_in_dir2'] Identical files : ['common_file'] Differing files : ['not_the_same'] Common subdirectories : ['common_dir'] Common funny cases : ['file_in_dir1'] None diff example/dir1 example/dir2 Only in example/dir1 : ['dir_only_in_dir1', 'file_only_in_dir1'] Only in example/dir2 : ['dir_only_in_dir2', 'file_only_in_dir2'] Identical files : ['common_file'] Differing files : ['not_the_same'] Common subdirectories : ['common_dir'] Common funny cases : ['file_in_dir1'] diff example/dir1\common_dir example/dir2\common_dir Common subdirectories : ['dir1', 'dir2'] diff example/dir1\common_dir\dir1 example/dir2\common_dir\dir1 Identical files : ['common_file', 'file_in_dir1', 'file_only_in_dir1', 'not_the_same'] Common subdirectories : ['common_dir', 'dir_only_in_dir1'] diff example/dir1\common_dir\dir1\common_dir example/dir2\common_dir\dir1\common_dir diff example/dir1\common_dir\dir1\dir_only_in_dir1 example/dir2\common_dir\dir1\dir_only_in_dir1 diff example/dir1\common_dir\dir2 example/dir2\common_dir\dir2 Identical files : ['common_file', 'file_only_in_dir2', 'not_the_same'] Common subdirectories : ['common_dir', 'dir_only_in_dir2', 'file_in_dir1'] diff example/dir1\common_dir\dir2\common_dir example/dir2\common_dir\dir2\common_dir diff example/dir1\common_dir\dir2\dir_only_in_dir2 example/dir2\common_dir\dir2\dir_only_in_dir2 diff example/dir1\common_dir\dir2\file_in_dir1 example/dir2\common_dir\dir2\file_in_dir1 None
您可以进一步尝试第 1 点中提到的所有命令,看看每个方法的行为如何。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

