Script launches exiftool and shows Creation Date/Time from image files

This commit is contained in:
2026-04-19 08:39:13 +03:00
parent 0124f0f7a8
commit ba7a549f6f
+54 -13
View File
@@ -1,27 +1,56 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os import os
import sys import sys
import subprocess
def get_exif_date(file_path):
"""
Uses exiftool to extract the File Creation Date/Time (CreateDate).
Returns the formatted date string or an error message if extraction fails.
"""
# Use exiftool to extract the CreateDate tag.
# We use -d to define the desired output format: YYYY-MM-DD HH:MM:SS
try:
# Command: exiftool -d "Format" -CreateDate "file_path"
# The -d option allows specifying the desired output format.
result = subprocess.run(
['exiftool', '-d', "%Y-%m-%d %H:%M:%S", '-CreateDate', file_path],
capture_output=True,
text=True,
check=True
)
# The result should contain the date string on the first line.
date_string = result.stdout.strip()
if date_string:
# Clean up potential trailing units or extra metadata lines
return date_string.split('\n')[0].strip()
return "Date not found in metadata."
except subprocess.CalledProcessError as e:
# This handles cases where exiftool fails (e.g., corrupted file)
return f"ERROR: exiftool failed. Check file integrity or permissions. (Details: {e.stderr.strip()})"
except FileNotFoundError:
# This handles cases where 'exiftool' command is not found
return "CRITICAL ERROR: exiftool command not found. Please ensure exiftool is installed and in your system PATH."
def scan_photos(root_dir): def scan_photos(root_dir):
""" """
Recursively scans the given directory and lists all specified photo file types. Recursively scans the given directory, extracts EXIF date, and prints file details.
""" """
# Define accepted extensions (in lowercase) # Define accepted extensions (in lowercase)
accepted_extensions = ( accepted_extensions = (
'.jpg', '.jpeg', '.raf', '.dng', '.raw', '.cr2', '.cr3' '.jpg', '.jpeg', '.dng', '.raw', '.cr2', '.cr3', '.raf'
) )
print(f"--- Starting scan in: {root_dir} ---") print(f"--- Starting photo import scan in: {root_dir} ---")
found_files = [] found_files = []
# 1. Find all files
try: try:
for foldername, subfolders, filenames in os.walk(root_dir): for foldername, subfolders, filenames in os.walk(root_dir):
for filename in filenames: for filename in filenames:
# Get the full path
full_path = os.path.join(foldername, filename) full_path = os.path.join(foldername, filename)
# Check the file extension # Check the file extension
# os.path.splitext splits filename into (root, extension)
_, ext = os.path.splitext(filename) _, ext = os.path.splitext(filename)
# Convert extension to lowercase for case-insensitive matching # Convert extension to lowercase for case-insensitive matching
@@ -29,17 +58,30 @@ def scan_photos(root_dir):
found_files.append(full_path) found_files.append(full_path)
except FileNotFoundError: except FileNotFoundError:
print(f"Error: The path '{root_dir}' was not found. Please check the drive letter.") print(f"\nFATAL ERROR: The path '{root_dir}' was not found. Please check the drive letter.")
return return
except Exception as e: except Exception as e:
print(f"An unexpected error occurred: {e}") print(f"\nAN UNEXPECTED ERROR OCCURRED DURING DIRECTORY TRAVERSAL: {e}")
return return
if found_files: if found_files:
print("\n--- Files Found ---") print("\n========================================================")
print("--- File Name & Creation Date/Time ---")
print("========================================================\n")
processed_count = 0
for file_path in found_files: for file_path in found_files:
print(file_path) # Extract the date using the external tool
print(f"\n--- Scan complete. Found {len(found_files)} files. ---") date_time = get_exif_date(file_path)
# Print the file name and the date/time
print(f"File Name: {os.path.basename(file_path)}")
print(f"Creation Date/Time: {date_time}")
print("-" * 40)
processed_count += 1
print(f"\n========================================================")
print(f"--- Scan complete. Processed {processed_count} files. ---")
else: else:
print("\n--- Scan complete. No specified photo files found in this directory or its subdirectories. ---") print("\n--- Scan complete. No specified photo files found in this directory or its subdirectories. ---")
@@ -54,9 +96,8 @@ if __name__ == "__main__":
# The first argument (index 1) is the path # The first argument (index 1) is the path
target_path = sys.argv[1] target_path = sys.argv[1]
# Ensure the path ends with a directory separator if it's not empty # Ensure the path ends with a directory separator
# This helps when the user types "Q:" instead of "Q:\"
if not target_path.endswith(os.sep): if not target_path.endswith(os.sep):
target_path = target_path + os.sep target_path = target_path + os.sep
scan_photos(target_path) scan_photos(target_path)