Python| filecmp.cmpfiles() 方法
Python中的Filecmp 模块提供了比较文件和目录的功能。该模块属于 Python 的标准实用程序模块。除了其中的数据之外,该模块还考虑文件和目录的属性以进行比较。
Python中的filecmp.cmpfiles()方法用于比较两个目录中的文件。使用此方法可以比较多个文件。此方法返回三个文件名列表,即匹配、不匹配和错误。匹配列表包含比较匹配的文件列表,不匹配列表包含那些不匹配的文件的名称,错误列表包含无法比较的文件的名称。
此方法默认执行浅比较(默认为浅 = True),这意味着仅比较文件的 os.stat() 签名(如大小、修改日期等),如果它们具有相同的签名,则认为文件是与文件内容无关。如果将 shallow 设置为 False,则通过比较文件的内容来进行比较。
Syntax: filecmp.cmpfiles(dir1, dir2, common, shallow = True)
Parameter:
dir1: The path of first directory. It can be a string, bytes or os.PathLike object representing the path of the directory.
dir2: The path of second directory. It can be a string, bytes or os.PathLike object representing the path of the directory.
common: A list representing the names of the files that will be compared in dir1 and dir2.
shallow (optional): A bool value ‘True’ or ‘False’. The default value of this parameter is True. If its value is True then only the metadata of files are compared. If False then the contents of the files are compared.
Return Type: This method returns a tuple of three lists which represents match, mismatch and errors lists.
例如:
filecmp.cmpfiles(dir1, dir2, [file1, file2, fil3]) will compare dir1/file1 with dir2/file1, dir1/file2 with dir2/file2 and dir1/file3 with dir2/file3 and will return match, mismatch and errors list.
示例:使用 filecmp.cmpfiles() 方法比较两个目录中的文件。
Python3
# Python program to explain filecmp.cmpfiles() method
# importing filecmp module
import filecmp
# Path of first directory
dir1 = "/home / User / Documents"
# Path of second directory
dir2 = "/home / User / Desktop"
# Common files
common = ["file1.txt", "file2.txt", "file3.txt"]
# Shallow compare the files
# common in both directories
match, mismatch, errors = filecmp.cmpfiles(dir1, dir2, common)
# Print the result of
# shallow comparison
print("Shallow comparison:")
print("Match :", match)
print("Mismatch :", mismatch)
print("Errors :", errors, "\n")
# Compare the
# contents of both files
# (i.e deep comparison)
match, mismatch, errors = filecmp.cmpfiles(dir1, dir2, common,
shallow = False)
# Print the result of
# deep comparison
print("Deep comparison:")
print("Match :", match)
print("Mismatch :", mismatch)
print("Errors :", errors)
Shallow comparison:
Match : ['file1.txt', 'file2.txt', 'file3.txt']
Mismatch : []
Errors : []
Deep comparison:
Match : ['file1.txt', 'file2.txt']
Mismatch : ['file3.txt']
Errors : []