识别文件夹及子文件夹中的重复文件
我刚开始学习Python,还是个新手。
我想从我的主文件夹里的文件中找出独特的文件,也就是xx文件夹里的文件,以及子文件夹yy里的文件。重复的文件可能有不同的文件名。
i.e. E:/username/Desktop/xx/filename.pdf
E:/username/Desktop/xx/filename1.pdf
E:/username/Desktop/xx/yy/filename1_23.pdf
重复的文件有filename1.pdf和file_name1_23.pdf。我希望得到一个独特文件的列表。如果有重复的文件,就取第一个文件。
期望的输出结果
i.e.['E:/username/Desktop/xx/filename.pdf',
'E:/username/Desktop/xx/filename1.pdf']
问题是这些代码可以运行,但无法识别独特的文件。你能帮我检查一下我的代码逻辑问题吗?
非常感谢你的时间。
import os
import fitz
path = 'E:/username/Desktop/xx'
pdf_paths = [os.path.join(root, name)
for root, dirs, files in os.walk(path)
for name in files
if name.endswith('.pdf')]
def extract_text_from_pdf(pdf_path):
text = ''
pdf_document = fitz.open(pdf_path)
for page_num in range(pdf_document.page_count):
page = pdf_document.load_page(page_num)
text += page.get_text()
pdf_document.close()
return text
def compare_pdfs(pdf_path1, pdf_path2):
text1 = extract_text_from_pdf(pdf_path1)
text2 = extract_text_from_pdf(pdf_path2)
if text1==text2:
return True
else:
return False
def compare_multiple_pdfs(pdf_paths):
unique_files = []
for i in range(len(pdf_paths)):
for j in range(i+1, len(pdf_paths)):
pdf_path1 = pdf_paths[i]
pdf_path2 = pdf_paths[j]
if compare_pdfs(pdf_path1, pdf_path2):
for existing_file in unique_files:
if compare_pdfs(pdf_path1, existing_file):
break
else:
unique_files.append(pdf_path1)
else:
for existing_file in unique_files:
if compare_pdfs(pdf_path1, existing_file) and compare_pdfs(pdf_path2, existing_file):
break
elif compare_pdfs(pdf_path1, existing_file):
unique_files.append(pdf_path2)
elif compare_pdfs(pdf_path2, existing_file):
unique_files.append(pdf_path1)
else:
unique_files.append(pdf_path1)
unique_files.append(pdf_path2)
return unique_files
compare_multiple_pdfs(pdf_paths)
1 个回答
2
你可以为每个文件计算一个哈希值,然后把这些哈希值进行比较。简单来说,哈希值对于每个输入都是独一无二的,在这个情况下,它就像是一个唯一的标识符。
大概是这样的:
import os
import hashlib
from collections import defaultdict
def file_hash(filepath):
hasher = hashlib.sha256()
with open(filepath, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hasher.update(chunk)
return hasher.hexdigest()
def find_duplicate_files(directory):
duplicates = defaultdict(list)
for root, _, files in os.walk(directory):
for file in files:
if file.lower().endswith(".pdf"):
file_path = os.path.join(root, file)
file_checksum = file_hash(file_path)
duplicates[file_checksum].append(file_path)
return {k: v for k, v in duplicates.items() if len(v) > 1}
directory = "" # <= add the path to your files here
duplicate_files = find_duplicate_files(directory)
if duplicate_files:
print("duplicate files found:")
for hash_value, files in duplicate_files.items():
print(f"hash: {hash_value}")
for file_path in files:
print(f"- {file_path}")
else:
print("no duplicate files found")
如果发现了重复的文件,这段代码会输出:
duplicate files found:
hash: e745ece17e34fd40e1f202ce8956cba607b60fa0095a1b2747f4b8e3611f75e5
- directory/file1.pdf
- directory/file2.pdf