Python 代码:使用哈希值查找两个文件夹中的重复文件
以下是一个利用哈希值检查并提取两个文件夹内部所有重复文件的Python代码示例:\n\npython\nimport os\nimport hashlib\n\ndef get_file_hash(file_path):\n # 计算文件的哈希值\n with open(file_path, 'rb') as file:\n data = file.read()\n file_hash = hashlib.md5(data).hexdigest()\n return file_hash\n\ndef find_duplicate_files(folder1, folder2):\n # 获取文件夹内所有文件路径\n files1 = [os.path.join(folder1, file) for file in os.listdir(folder1) if os.path.isfile(os.path.join(folder1, file))]\n files2 = [os.path.join(folder2, file) for file in os.listdir(folder2) if os.path.isfile(os.path.join(folder2, file))]\n\n # 对文件进行哈希值比较\n hash_dict = {}\n duplicate_files = []\n\n for file in files1 + files2:\n file_hash = get_file_hash(file)\n if file_hash in hash_dict:\n duplicate_files.append(file)\n duplicate_files.append(hash_dict[file_hash])\n else:\n hash_dict[file_hash] = file\n\n return duplicate_files\n\n# 测试代码\nfolder1 = 'path/to/folder1'\nfolder2 = 'path/to/folder2'\nduplicate_files = find_duplicate_files(folder1, folder2)\n\nprint('重复文件:')\nfor file in duplicate_files:\n print(file)\n\n\n在上述代码中,get_file_hash函数用于计算文件的哈希值。find_duplicate_files函数用于比较两个文件夹内的文件,并返回重复的文件路径列表。在测试代码中,将要比较的两个文件夹路径传递给find_duplicate_files函数,并打印出重复文件的路径。请将folder1和folder2变量替换为实际的文件夹路径。
原文地址: https://www.cveoy.top/t/topic/pvFE 著作权归作者所有。请勿转载和采集!