General Task Automation

General Task Automation in Python: Web scraping is just one type of automation. Python is also amazing at handling the files and folders on your computer.

Concept Explanation

Web scraping is just one type of automation. Python is also amazing at handling the files and folders on your computer.

  • Need to rename 5,000 photos?
  • Need to delete all PDF files older than 30 days?
  • Need to move every file containing the word "Tax" into a specific folder?

Python's built-in os, shutil, and pathlib modules are your best friends for these tasks. They turn hours of manual clicking into a 1-second script.


Syntax or Core Structure

The os and shutil modules

  • os: Interacting with the Operating System (listing files, deleting, checking paths).
  • shutil: High-level file operations (copying, moving, zipping).
import os
import shutil

# 1. Get current directory
print(os.getcwd())

# 2. List all files
files = os.listdir('.')

# 3. Create a folder
if not os.path.exists('Backups'):
    os.mkdir('Backups')

# 4. Copy a file
shutil.copy('data.txt', 'Backups/data_copy.txt')

Code Example #1 (Basic)

Organizing files into folders by their extension.

import os
import shutil

def organize_files(folder_path):
    for filename in os.listdir(folder_path):
        if "." in filename:
            ext = filename.split(".")[-1]
            dest_folder = os.path.join(folder_path, ext)
            
            if not os.path.exists(dest_folder):
                os.makedirs(dest_folder)
            
            shutil.move(os.path.join(folder_path, filename), 
                        os.path.join(dest_folder, filename))

# organize_files('C:/Users/Downloads')

Code Example #2 (Intermediate)

Searching for text inside 1,000 files.

import os

def find_text_in_files(directory, search_query):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(".txt"):
                path = os.path.join(root, file)
                with open(path, 'r') as f:
                    if search_query in f.read():
                        print(f"Match found in: {path}")

# find_text_in_files('./logs', 'ERROR 404')

Real World Example

Automatic Backup & Zip: Zipping a project folder every night and adding a timestamp to the filename.

import shutil
import datetime

def backup_project(folder_to_zip, destination_dir):
    date = datetime.datetime.now().strftime("%Y-%m-%d")
    archive_name = f"Project_Backup_{date}"
    
    # Creates 'Project_Backup_2024-05-20.zip'
    shutil.make_archive(archive_name, 'zip', folder_to_zip)
    
    # Move it to the backup drive
    shutil.move(f"{archive_name}.zip", destination_dir)
    print("Backup Complete!")

# backup_project('./my_code', 'D:/Backups')

Common Mistakes

  1. Hardcoding Paths: Using C:\Users\Harsh\Desktop. This script will only work on your computer. Use os.path.expanduser('~') or pathlib to make paths work on any machine.
  2. Accidental Deletion: Writing os.remove() inside a loop without testing it first. Always use print() instead of remove() until you are 100% sure the script is selecting the right files.
  3. Permission Denied: Trying to delete or move a file that is currently open in another program (like Word or Excel).

Best Practices

  • Use Pathlib: Modern Python (3.4+) prefers the pathlib module over os.path. It treats paths as objects, making them much easier to join and manipulate.
  • Dry Runs: Include a "Dry Run" flag in your automation scripts that just prints what it would do without actually touching your files.
  • Logging: Use the logging module to record every file your script moves or deletes, so you can track what happened if something goes wrong.

Practice Exercises

  1. The Extension Counter: Write a script that counts how many .jpg, .png, and .pdf files are in your current directory.
  2. The Bulk Renamer: Create 10 empty text files named test_1.txt, test_2.txt, etc. Write a script that renames them to final_1.txt, final_2.txt, etc.
  3. The Space Saver: Write a script that finds every file larger than 10MB in your Documents folder and prints their names and sizes.