-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathduplicate_file_finder.py
More file actions
66 lines (50 loc) · 1.75 KB
/
Copy pathduplicate_file_finder.py
File metadata and controls
66 lines (50 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import os # work with files and folders
import hashlib # create hashes (file fingerprints)
# Folder to scan for duplicates
folder_path = os.path.expanduser("~/Downloads") # change if needed
# Function to calculate a file's hash
# This creates a unique "fingerprint" based on file content
def get_file_hash(file_path):
hasher = hashlib.md5() # MD5 is fast and fine for duplicate detection
# Open file in binary mode (important!)
with open(file_path, "rb") as file:
# Read the file in chunks (good for large files)
while True:
chunk = file.read(4096)
if not chunk:
break
hasher.update(chunk)
# Return the final hash value
return hasher.hexdigest()
# Dictionary to store hashes we've seen
# Format: {hash: file_path}
seen_files = {}
# List to store duplicates
duplicates = []
# Go through all files in the folder
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
# Skip folders
if os.path.isdir(file_path):
continue
try:
# Get the file's hash
file_hash = get_file_hash(file_path)
# Check if we've seen this hash before
if file_hash in seen_files:
# Duplicate found!
duplicates.append((file_path, seen_files[file_hash]))
else:
# First time seeing this file
seen_files[file_hash] = file_path
except Exception as e:
print(f"Error reading {filename}: {e}")
# Print results
print("\nDuplicate files found:\n")
if not duplicates:
print("No duplicates found 🎉")
else:
for duplicate, original in duplicates:
print(f"Duplicate: {duplicate}")
print(f"Original: {original}")
print("-" * 40)