Python:filecmp.cmp() 方法
Python中的Filecmp 模块提供了比较文件和目录的功能。该模块属于 Python 的标准实用程序模块。除了其中的数据之外,该模块还考虑文件和目录的属性以进行比较。
Python中的filecmp.cmp()
方法用于比较两个文件。默认情况下,此方法执行浅比较(默认为shallow = True
),这意味着仅比较两个文件的os.stat()
签名(如大小、修改日期等),如果它们具有相同的签名,则认为文件无论文件的内容如何,都是平等的。如果将shallow
设置为False
,则通过比较两个文件的内容来完成比较。
Syntax: filecmp.cmp(file1, file2, shallow = True)
Parameter:
file1: The path of first file to be compared. It can be a string, bytes, os.PathLike object or an integer representing the path of the file.
file2: The path of second file to be compared. It can be a string, bytes, os.PathLike object or an integer representing the path of the file.
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 bool value True if specified files are equal or False if they are not.
# Python program to demonstrate
# filecmp.cmp() method
import filecmp
# Path of first file
file1 = "/home/geeks/Desktop/gfg/data.txt"
# Path of second file
file2 = "/home/geeks/Desktop/gfg/gfg.txt"
# Compare the os.stat()
# signature i.e the metadata
# of both files
comp = filecmp.cmp(file1, file2)
# Print the result of comparison
print(comp)
# Compare the
# contents of both files
comp = filecmp.cmp(file1, file2, shallow = False)
# Print the result of comparison
print(comp)
False
True
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。