|
| 1 | +import os |
| 2 | +import hashlib |
| 3 | + |
| 4 | +def get_file_hash(filepath): |
| 5 | + """Return the MD5 hash of a file.""" |
| 6 | + hasher = hashlib.md5() |
| 7 | + with open(filepath, 'rb') as f: |
| 8 | + buf = f.read() |
| 9 | + hasher.update(buf) |
| 10 | + return hasher.hexdigest() |
| 11 | + |
| 12 | +def find_duplicates(directory, min_size=0): |
| 13 | + """Find duplicate files in a directory.""" |
| 14 | + hashes = {} |
| 15 | + duplicates = {} |
| 16 | + |
| 17 | + for dirpath, dirnames, filenames in os.walk(directory): |
| 18 | + for filename in filenames: |
| 19 | + filepath = os.path.join(dirpath, filename) |
| 20 | + if os.path.getsize(filepath) >= min_size: |
| 21 | + file_hash = get_file_hash(filepath) |
| 22 | + if file_hash in hashes: |
| 23 | + duplicates.setdefault(file_hash, []).append(filepath) |
| 24 | + # Also ensure the original file is in the duplicates list |
| 25 | + if hashes[file_hash] not in duplicates[file_hash]: |
| 26 | + duplicates[file_hash].append(hashes[file_hash]) |
| 27 | + else: |
| 28 | + hashes[file_hash] = filepath |
| 29 | + |
| 30 | + return {k: v for k, v in duplicates.items() if len(v) > 1} |
| 31 | + |
| 32 | +def main(): |
| 33 | + directory = input("Enter the directory to scan for duplicates: ") |
| 34 | + min_size = int(input("Enter the minimum file size to consider (in bytes, default is 0): ") or "0") |
| 35 | + |
| 36 | + duplicates = find_duplicates(directory, min_size) |
| 37 | + |
| 38 | + if not duplicates: |
| 39 | + print("No duplicates found.") |
| 40 | + return |
| 41 | + |
| 42 | + print("\nDuplicates found:") |
| 43 | + for _, paths in duplicates.items(): |
| 44 | + for path in paths: |
| 45 | + print(path) |
| 46 | + print("------") |
| 47 | + |
| 48 | + action = input("\nChoose an action: (D)elete, (M)ove, (N)o action: ").lower() |
| 49 | + |
| 50 | + if action == "d": |
| 51 | + for _, paths in duplicates.items(): |
| 52 | + for path in paths[1:]: # Keep the first file, delete the rest |
| 53 | + os.remove(path) |
| 54 | + print(f"Deleted {path}") |
| 55 | + |
| 56 | + elif action == "m": |
| 57 | + target_dir = input("Enter the directory to move duplicates to: ") |
| 58 | + if not os.path.exists(target_dir): |
| 59 | + os.makedirs(target_dir) |
| 60 | + |
| 61 | + for _, paths in duplicates.items(): |
| 62 | + for path in paths[1:]: # Keep the first file, move the rest |
| 63 | + target_path = os.path.join(target_dir, os.path.basename(path)) |
| 64 | + os.rename(path, target_path) |
| 65 | + print(f"Moved {path} to {target_path}") |
| 66 | + |
| 67 | + else: |
| 68 | + print("No action taken.") |
| 69 | + |
| 70 | +if __name__ == "__main__": |
| 71 | + main() |
0 commit comments