Explain Codes LogoExplain Codes Logo

Rename multiple files in a directory in Python

python
rename
bulk-renaming
file-system
Anton ShumikhinbyAnton Shumikhin·Sep 4, 2024
TLDR

Perform bulk renaming of files using Python script and os module. Here's how to prefix filenames with "new_" in a specific directory:

import os for filename in os.listdir('.'): if filename.endswith('.txt'): # We only want .txt files os.rename(filename, f'new_{filename}') # Say hi to your new name!

This script identifies .txt files in the current directory (".") and prefixes them with "new_". Tailor the if-condition and new filename as you require.

Advanced bulk renaming

Removing prefixes without collisions

Want to strip a prefix like "CHEESE_" from filenames and ensure no overwrites? Here's your cheese slicer:

import os for filename in os.listdir('.'): if filename.startswith('CHEESE_'): # That's a lot of cheese! new_filename = filename.replace('CHEESE_', '', 1) if not os.path.exists(new_filename): # Avoid chaos by ensuring unique names os.rename(filename, new_filename) # Say cheese no more!

This script employs fledged prefix removal without hardcoding string lengths, replacing just the first occurrence.

Using regex for complex patterns

When dealing with complex name patterns, you'll need the re module. Here's the magic wand:

import os import re pattern = re.compile(r'^(CHEESE_)(.*)') # We love regex, don't we? for filename in os.listdir('.'): match = pattern.match(filename) if match: new_filename = match.group(2) if not os.path.exists(new_filename): # I have a bad feeling about duplicates! os.rename(filename, new_filename) # Begone, CHEESE_

This snippet deftly selects the desired filename segments for renaming while staying wary of name duplication.

Deep renaming with os.walk

To change filenames within subdirectories, here's the master key:

import os for root, dirs, files in os.walk('.'): # We're going down the rabbit hole! for filename in files: if 'CHEESE_' in filename: new_filename = filename.replace('CHEESE_', '') original_path = os.path.join(root, filename) # Keep track of where we are new_path = os.path.join(root, new_filename) if not os.path.exists(new_path): # Careful, do not overwrite! os.rename(original_path, new_path) # Hasta la vista, CHEESE_

This wizardry iterates through all subdirectories, renaming files but remembering their original directory path.

Pro-tips and future-proofing

Be ready for unexpected guests

Prepare for unforeseen errors or exceptions:

try: os.rename(original_path, new_path) #trust me, I got this! except OSError as e: print(f"Error: {e}") # Oops! Didn't see that coming.

This code acts as your safety net against surprising issues like permission denial, or files being already in use.

Using pathlib: The trendy way

Opt for pathlib to rename files:

from pathlib import Path folder = Path('.') for file_path in folder.glob('*.txt'): file_path.rename(f'new_{file_path.name}') # The new cool kid in town!

Here, glob patterns come handy for matching files, and object-oriented paths.

Backup before hitting 'Go!'

Always create a backup:

import shutil shutil.copy2(original_path, backup_path) # Just making sure we're safe!

This precaution provides a safety net before committing changes, preventing data loss or "Oh no!" moments.