Automating File Management with Python

Loading

Managing files manually can be time-consuming. Python provides powerful libraries like os, shutil, pathlib, and schedule to automate file-related tasks such as:
Creating, renaming, and deleting files/folders
Moving and organizing files by type
Backing up important files
Monitoring file changes
Scheduling automatic cleanups


1. Setting Up the Environment

Before automating, install necessary libraries:

pip install watchdog schedule

Modules Used:

  • os → Handle file paths and directories
  • shutil → Copy, move, delete files
  • pathlib → Work with file paths in an object-oriented way
  • watchdog → Monitor file changes
  • schedule → Automate tasks

2. Creating and Renaming Files/Folders

Creating a new file and writing content

with open("example.txt", "w") as file:
file.write("This is an automated file.\n")
print("File created successfully!")

Creating a new folder

import os

folder_name = "New_Folder"
if not os.path.exists(folder_name):
os.mkdir(folder_name)
print(f"Folder '{folder_name}' created!")

Renaming a file

os.rename("example.txt", "renamed_file.txt")
print("File renamed successfully!")

Now you can create and rename files/folders!


3. Moving and Organizing Files by Type

Sort files into folders based on extension

import os
import shutil

source_folder = "Downloads"
destination_folder = {
"Images": [".jpg", ".png", ".gif"],
"Documents": [".pdf", ".docx", ".txt"],
"Videos": [".mp4", ".avi"]
}

for file in os.listdir(source_folder):
file_path = os.path.join(source_folder, file)
if os.path.isfile(file_path):
for folder, extensions in destination_folder.items():
if file.lower().endswith(tuple(extensions)):
folder_path = os.path.join(source_folder, folder)
os.makedirs(folder_path, exist_ok=True)
shutil.move(file_path, folder_path)
print(f"Moved {file} to {folder_path}")

Now files are organized automatically!


4. Copying and Deleting Files

Copy a file to another location

shutil.copy("renamed_file.txt", "backup/renamed_file.txt")
print("File copied successfully!")

Delete a file

os.remove("renamed_file.txt")
print("File deleted successfully!")

Delete an empty folder

os.rmdir("New_Folder")
print("Folder deleted successfully!")

Delete a folder with all files

shutil.rmtree("backup")
print("Folder and its contents deleted!")

Now files and folders are copied and deleted efficiently!


5. Monitoring File Changes (Watchdog)

To track file modifications:

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class FileChangeHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f"File {event.src_path} has been modified.")

def on_created(self, event):
print(f"File {event.src_path} has been created.")

def on_deleted(self, event):
print(f"File {event.src_path} has been deleted.")

observer = Observer()
observer.schedule(FileChangeHandler(), path=".", recursive=True)
observer.start()

try:
while True:
pass
except KeyboardInterrupt:
observer.stop()
observer.join()

Now file modifications are being tracked!


6. Backing Up Important Files Automatically

Copy files to a backup folder

import shutil
import os
from datetime import datetime

source_folder = "Documents"
backup_folder = f"Backup_{datetime.now().strftime('%Y%m%d')}"

os.makedirs(backup_folder, exist_ok=True)

for file in os.listdir(source_folder):
file_path = os.path.join(source_folder, file)
shutil.copy(file_path, backup_folder)
print(f"Backed up {file} to {backup_folder}")

Now files are backed up automatically!


7. Scheduling Automatic File Cleanup

Delete files older than 30 days

import os
import time

folder_path = "Downloads"
days = 30
now = time.time()

for file in os.listdir(folder_path):
file_path = os.path.join(folder_path, file)
if os.path.isfile(file_path) and now - os.path.getmtime(file_path) > days * 86400:
os.remove(file_path)
print(f"Deleted {file}")

Now old files are automatically cleaned up!


8. Automating File Management with Scheduling

Run tasks at a specific time

import schedule
import time

def clean_downloads():
print("Running cleanup script...")
# Add cleanup or backup functions here

schedule.every().day.at("23:00").do(clean_downloads)

while True:
schedule.run_pending()
time.sleep(60)

Now file management tasks run on schedule!

Leave a Reply

Your email address will not be published. Required fields are marked *