如何在Python中比较文件
问题。
你需要在Python中比较文件。
解决方案。
Python中的`filecmp`模块可以用来比较文件和目录。1.
cmp(file1, file2[, shallow])
`filecmp.cmp()` 比较文件`file1`和`file2`,如果相同则返回`True`,否则返回`False`。默认情况下,具有`os.stat()`返回的相同属性的文件被认为是相等的。如果未提供`shallow`参数(或为`True`),则具有相同stat签名的文件被认为是相等的。
cmpfiles(dir1, dir2, common[, shallow])
`filecmp.cmpfiles()` 比较两个目录`dir1`和`dir2`中`common`列表中包含的文件的内容。`cmpfiles`返回一个包含三个列表的元组 - `match`、`mismatch`、`errors`文件名。
`match` - 列出在两个目录中都相同的文件。
`mismatch` - 列出不匹配的文件。
`errors` - 列出由于某种原因无法比较的文件。
dircmp(dir1, dir2 [, ignore[, hide]])
`filecmp.dircmp()` 创建一个目录比较对象,可用于对目录`dir1`和`dir2`执行各种比较操作。
`ignore` - 忽略要忽略的文件名列表,默认值为['RCS','CVS','tags']。
`hide` - 要隐藏的文件名列表,默认为[os.curdir, os.pardir](在UNIX上为['.', '..'])。
`filecmp.dircmp`的实例实现了以下方法,这些方法将详细的报告打印到`sys.stdout`
`report()`:打印两个目录之间的比较。
`report_partial_closure()`:打印两个目录以及两个`目录`的直接子目录的比较。
`report_full_closure()`:打印两个目录、所有子目录、`这些子目录`的所有子目录等的比较(即递归)。
`left_list`:在目录路径1中找到的文件和子目录,不包括`hidelist`中的元素。
`right_list`:在目录路径2中找到的文件和子目录,不包括`hidelist`中的元素。
`common`:同时存在于目录路径1和目录路径2中的文件和子目录。
`left_only`:仅存在于目录路径1中的文件和子目录。
`right_only`:仅存在于目录路径2中的文件和子目录。
`common_dirs`:同时存在于目录路径1和目录路径2中的子目录。
`common_files`:同时存在于目录路径1和目录路径2中的文件。
`same_files`:内容在目录路径1和目录路径2中都相同的文件的路径。
`diff_files`:同时存在于目录路径1和目录路径2中,但内容不同的文件的路径。
`funny_files`:同时存在于目录路径1和目录路径2中,但由于某种原因无法比较的文件的路径。
`subdirs`:一个字典,将`common_dirs`中的名称映射到`dircmp`对象。
准备用于比较的测试数据。
import os
# prepare test data
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
# prepare test data
def makedirectory(directory_name):
"""
Function: make directories
params : input directory
"""
if not os.path.exists(directory_name):
os.mkdir(directory_name)
# Get current working directory
present_directory = os.getcwd()
# change to directory provided
os.chdir(directory_name)
# Make two directories
os.mkdir('dir1')
os.mkdir('dir2')
# Make two same subdirectories
os.mkdir('dir1/common_dir')
os.mkdir('dir2/common_dir')
# Make two different subdirectories
os.mkdir('dir1/dir_only_in_dir1')
os.mkdir('dir2/dir_only_in_dir2')
# Make a unqiue file one each in directory
makefile('dir1/file_only_in_dir1')
makefile('dir2/file_only_in_dir2')
# Make a unqiue file one each in directory
makefile('dir1/common_file', 'Hello, Writing Same Content')
makefile('dir2/common_file', 'Hello, Writing Same Content')
# Make a non unqiue file one each in directory
makefile('dir1/not_the_same')
makefile('dir2/not_the_same')
makefile('dir1/file_in_dir1', 'This is a file in 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示例。`shallow`参数告诉`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
`cmpfiles`示例
使用`cmpfiles()`比较两个目录中的一组文件,而不递归。
import filecmp
import os
# Determine the items that exist in both directories.
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}')
# Now, let us compare the directories
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中提到的所有命令,以查看每种方法的行为。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP