Mastering Python File Handling: 3 Practical Tips

Hello everyone! I’ve noticed many of you struggle with processing a large number of files, so today I’m sharing some practical Python tips to make file handling easy and efficient.

Batch Rename Files for Better Management

In daily work, we often encounter situations where we need to batch rename files. For example, changing a photo file like “IMG_20240108_001.jpg” to a more understandable format.


import os

def batch_rename(folder_path, prefix='photo'):

    # Get all files in the folder
    files = os.listdir(folder_path)
    
    for index, old_name in enumerate(files, 1):
        # Get file extension
        file_ext = os.path.splitext(old_name)[1]
        # Construct new file name
        new_name = f"{prefix}_{index:03d}{file_ext}"
        
        # Concatenate full file path
        old_path = os.path.join(folder_path, old_name)
        new_path = os.path.join(folder_path, new_name)
        
        # Rename file
        os.rename(old_path, new_path)

# Example usage
batch_rename('photos', 'vacation')

💡 Tip: Before batch renaming, it’s recommended to back up the original files just in case something goes wrong.

Smart File Classification to End Folder Chaos

Sometimes, files of various types pile up in the downloads folder, which can be overwhelming. With just a few lines of Python code, you can easily classify your files.


import os
import shutil
from pathlib import Path

def classify_files(source_folder):
    # Define file type mappings
    file_types = {
        'images': ['.jpg', '.png', '.gif'],
        'documents': ['.pdf', '.doc', '.docx'],
        'videos': ['.mp4', '.avi', '.mov']
    }
    
    source_path = Path(source_folder)
    
    # Iterate through all files
    for file_path in source_path.iterdir():
        if file_path.is_file():
            # Get file extension
            file_ext = file_path.suffix.lower()
            
            # Determine file type and move
            for type_name, extensions in file_types.items():
                if file_ext in extensions:
                    # Create target folder
                    target_folder = source_path / type_name
                    target_folder.mkdir(exist_ok=True)
                    
                    # Move file
                    shutil.move(str(file_path), str(target_folder / file_path.name))
                    break

# Example usage
classify_files('downloads')

Batch Modify File Content for Easy Text Replacement

Need to uniformly modify certain content in a large number of text files? This script can save you a lot of time.


def batch_modify_content(folder_path, old_text, new_text):
    # Traverse all text files in the specified folder
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.txt'):  # You can modify the file type as needed
                file_path = os.path.join(root, file)
                
                # Read file content
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                # Replace content
                new_content = content.replace(old_text, new_text)
                
                # Write modified content
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(new_content)

# Example usage
batch_modify_content('documents', 'Old Company Name', 'New Company Name')

💡 Tip: For large files, it’s recommended to process them line by line to avoid memory overflow issues.

With these tips, file handling will no longer be a nightmare! Give it a try~

Mini Exercise: Try writing a script that finds all files modified in the last 7 days in a specified folder and copies them to a new folder.

Leave a Comment