Creating a script to find duplicate files, including videos and photos, requires comparing file contents or hashes to identify duplicates. Below is an example script in Python that does this. It scans a specified directory, checks for duplicates, and then moves the duplicates to a new folder named "lovebug".
Please note that you should take care with scripts that move or delete files to avoid unintentional data loss. Always back up your files before running such scripts, and test the script on a small set of files first.
import os
import hashlib
import shutil
def file_hash(filepath):
# A function to generate a hash of the file content for comparison
sha = hashlib.sha256()
with open(filepath, 'rb') as f:
while True:
block = f.read(65536)
if not block:
break
sha.update(block)
return sha.hexdigest()
def find_duplicates(root_dir):
# This function walks through all directories and compiles a list of duplicate files
hashes = {}
duplicates = []
for dirpath, dirnames, filenames in os.walk(root_dir):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
filehash = file_hash(filepath)
if filehash in hashes:
duplicates.append(filepath)
else:
hashes[filehash] = filepath
return duplicates
def move_duplicates(dupes, target_folder):
# This function moves the identified duplicates to the target folder
os.makedirs(target_folder, exist_ok=True)
for dupe in dupes:
# Generate a unique filename in case of name conflicts
basename = os.path.basename(dupe)
target_path = os.path.join(target_folder, basename)
counter = 1
while os.path.exists(target_path):
name, ext = os.path.splitext(basename)
target_path = os.path.join(target_folder, f"{name}_{counter}{ext}")
counter += 1
shutil.move(dupe, target_path)
# Specify the directory you want to scan for duplicates
root_directory = 'path_to_your_directory' # Replace with your directory
target_directory = os.path.join(root_directory, 'lovebug')
# Find and move duplicates
duplicates = find_duplicates(root_directory)
move_duplicates(duplicates, target_directory)
print(f"Duplicate files moved to {target_directory}.")
Before you run this script, replace 'path_to_your_directory' with the path to the