Group and rename image and videos with python
Hello, today I would like to share with you two Python scripts that I used to solve my problem. I had a folder where I randomly kept the pictures I took, and its size was about 100 GB. I didn't even know what was in it anymore. I created a code to group them according to the years and months taken.
If it can use the shooting date of the file, it groups it accordingly; if it cannot find it, it uses the creation date.
The other script, after all these processes are completed, names the files under the grouped folders as 1,2,3 according to the withdrawal date or the creation date.
Both scripts do not touch file extensions.
领英推荐
#arranger.py
import os
from PIL import Image
import shutil
from datetime import datetime
def organize_photos_and_videos(source_directory, target_base_directory):
for root, dirs, files in os.walk(source_directory):
for file in files:
file_path = os.path.join(root, file)
if file.lower().endswith(('.png', '.jpg', '.jpeg')):
try:
with Image.open(file_path) as img:
exif_data = img._getexif()
date_taken = exif_data.get(36867) if exif_data else None
except Exception as e:
print(f"Error reading EXIF data for {file}: {e}")
date_taken = None
elif file.lower().endswith(('.mp4', '.avi', '.mov')):
date_taken = None # You can add a custom method for video files
else:
continue
# If there is no withdrawal date, use creation date
if not date_taken:
creation_time = os.path.getctime(file_path)
date_taken = datetime.fromtimestamp(creation_time).strftime('%Y:%m:%d %H:%M:%S')
# Convert date from 'YYYY:MM:DD HH:MM:SS' format to 'YYYY\\MM' format
date_folder = date_taken[:7].replace(':', '\\')
type_folder = 'pic' if file.lower().endswith(('.png', '.jpg', '.jpeg')) else 'video'
target_folder = os.path.join(target_base_directory, date_folder, type_folder)
if not os.path.exists(target_folder):
os.makedirs(target_folder)
shutil.move(file_path, os.path.join(target_folder, file))
print(f"Moved {file} to {target_folder}")
# Source and destination folder paths
source_directory = 'E:\\pics'
target_base_directory = 'E:\\groupped'
organize_photos_and_videos(source_directory, target_base_directory)
and the other one;
#renamer.py
import os
from PIL import Image
import shutil
from datetime import datetime
def rename_files_based_on_date(source_directory):
for root, dirs, files in os.walk(source_directory, topdown=False):
file_details = []
# Collect withdrawal or creation date for each file
for file in files:
file_path = os.path.join(root, file)
extension = os.path.splitext(file)[1]
date_taken = None
if file.lower().endswith(('.png', '.jpg', '.jpeg')):
try:
with Image.open(file_path) as img:
exif_data = img._getexif()
date_taken = exif_data.get(36867) if exif_data else None
except Exception as e:
print(f"Error reading EXIF data for {file}: {e}")
if not date_taken: # If there is no withdrawal date, use the creation date
creation_time = os.path.getctime(file_path)
date_taken = datetime.fromtimestamp(creation_time).strftime('%Y:%m:%d %H:%M:%S')
file_details.append((file_path, date_taken, extension))
# Sort files by withdrawn or created date
file_details.sort(key=lambda x: x[1])
# Rename sorted files
for index, details in enumerate(file_details, start=1):
old_path = details[0]
new_name = f"{index}{details[2]}" # For example '1.jpg'
new_path = os.path.join(root, new_name)
if old_path == new_path: # If the new name is the same as the old name, skip
continue
if os.path.exists(new_path):
# If the target file already exists, rename it by adding "_1" to avoid name conflict
new_path_with_counter = os.path.join(root, f"{index}_1{details[2]}")
os.rename(old_path, new_path_with_counter)
print(f"Renamed {old_path} to {new_path_with_counter}")
else:
os.rename(old_path, new_path)
print(f"Renamed {old_path} to {new_path}")
# Use of
source_directory = 'E:\\pics'
rename_files_based_on_date(source_directory)