适用于学校上机考试,查看是否有抄袭的现象。使用SHA-256算法计算文件的哈希值,并比较两个文件是否相同。
import hashlib
def calculate_file_hash(file_path, block_size=65536):
sha256 = hashlib.sha256()
with open(file_path, 'rb') as file:
for block in iter(lambda: file.read(block_size), b''):
sha256.update(block)
return sha256.hexdigest()
def check_duplicate_files(file_path1, file_path2):
hash1 = calculate_file_hash(file_path1)
hash2 = calculate_file_hash(file_path2)
if hash1 == hash2:
print(f"The files {file_path1} and {file_path2} are duplicates.")
else:
print(f"The files {file_path1} and {file_path2} are not duplicates.")
# 示例用法
file_path_1 = 'path/to/file1.txt'
file_path_2 = 'path/to/file2.txt'
check_duplicate_files(file_path_1, file_path_2)