Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Move Files to Creation and Modification Date Named Directories using Python
In this article, we'll learn how to organize files by automatically moving them into directories named after their creation or modification dates using Python. This is useful for sorting large collections of files chronologically.
Understanding the Problem
When managing files, it's often helpful to organize them by date. We'll create a Python script that automatically moves files into folders named after their modification dates. If a date-specific folder doesn't exist, the script creates it first.
Algorithm
Step 1 Import necessary libraries:
os,shutil, anddatetimeStep 2 Define the source directory containing files to organize
Step 3 Change to the source directory and list all contents
Step 4 Loop through each file and directory in the source folder
Step 5 For subdirectories: move their contents to the main directory, then remove empty subdirectories
Step 6 For files: get modification date, create date-named directory if needed, and move the file
Complete Implementation
import os
import shutil
import datetime
# Define source directory (change this path to your directory)
source_directory = "/path/to/your/files"
try:
# Change to source directory
os.chdir(source_directory)
print(f"Working in directory: {os.getcwd()}")
# List all items in directory
all_items = os.listdir()
current_dir = os.getcwd()
# Process each item
for item in all_items:
item_path = os.path.join(current_dir, item)
if os.path.isdir(item_path):
# Handle subdirectories: move their files to main directory
print(f"Processing subdirectory: {item}")
sub_files = os.listdir(item_path)
for sub_file in sub_files:
sub_file_path = os.path.join(item_path, sub_file)
if os.path.isfile(sub_file_path):
shutil.move(sub_file_path, current_dir)
print(f" Moved {sub_file} to main directory")
# Remove empty subdirectory
if not os.listdir(item_path):
os.rmdir(item_path)
print(f" Removed empty directory: {item}")
else:
# Handle files: organize by modification date
mod_time = os.path.getmtime(item_path)
mod_date = datetime.datetime.fromtimestamp(mod_time)
# Create directory name (format: Month-Day-Year)
dir_name = mod_date.strftime("%b-%d-%Y")
dest_dir = os.path.join(current_dir, dir_name)
# Create directory if it doesn't exist
os.makedirs(dest_dir, exist_ok=True)
# Move file to date directory
dest_path = os.path.join(dest_dir, item)
shutil.move(item_path, dest_path)
print(f"Moved {item} to {dir_name}/")
print("\n? File organization completed successfully!")
except FileNotFoundError:
print("? Error: Source directory not found. Please check the path.")
except PermissionError:
print("? Error: Permission denied. Check file/directory permissions.")
except Exception as e:
print(f"? An error occurred: {e}")
Working in directory: /path/to/your/files Processing subdirectory: old_folder Moved document1.txt to main directory Moved image1.jpg to main directory Removed empty directory: old_folder Moved document1.txt to Jan-15-2024/ Moved image1.jpg to Jan-20-2024/ Moved report.pdf to Jan-20-2024/ Moved data.csv to Feb-01-2024/ ? File organization completed successfully!
Key Features
Date Format Uses "Month-Day-Year" format (e.g., "Jan-15-2024")
Directory Creation Automatically creates date directories if they don't exist
Subdirectory Handling Moves files from subdirectories to main directory first
Error Handling Includes proper exception handling for common errors
Customization Options
You can modify the date format by changing the strftime pattern ?
# Different date formats
dir_name = mod_date.strftime("%Y-%m-%d") # 2024-01-15
dir_name = mod_date.strftime("%Y-%B") # 2024-January
dir_name = mod_date.strftime("%b_%Y") # Jan_2024
print(f"Directory name: {dir_name}")
Directory name: Jan_2024
Conclusion
This Python script efficiently organizes files by moving them into directories named after their modification dates. It handles subdirectories, creates necessary folders automatically, and includes proper error handling for robust file management.
