Python
File Renaming
Directory Management
Programming
Automation

Rename multiple files in a directory in Python

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Renaming many files in Python is straightforward, but safe bulk renaming needs a little more discipline than a single os.rename call. The real concerns are predictable ordering, name collisions, and being clear about which files should change. A good batch rename script previews the result, uses explicit path handling, and avoids accidentally overwriting existing files.

A Simple pathlib Pattern

pathlib is a clean modern choice for filesystem work.

python
1from pathlib import Path
2
3folder = Path('reports')
4
5for path in folder.iterdir():
6    if path.is_file() and path.suffix == '.txt':
7        new_name = f'archived_{path.name}'
8        path.rename(path.with_name(new_name))

This prefixes every .txt file in reports with archived_.

Rename in a Stable Order

If the new names depend on numbering, sort the files first. Filesystem iteration order is not something you should rely on.

python
1from pathlib import Path
2
3folder = Path('images')
4files = sorted(p for p in folder.iterdir() if p.is_file())
5
6for index, path in enumerate(files, start=1):
7    new_name = f'image_{index:03d}{path.suffix}'
8    path.rename(path.with_name(new_name))

This produces names like image_001.jpg, image_002.jpg, and so on.

Preview Before Renaming

A dry run is often the difference between a useful utility and a destructive one.

python
1from pathlib import Path
2
3folder = Path('docs')
4files = sorted(p for p in folder.iterdir() if p.is_file())
5
6for index, path in enumerate(files, start=1):
7    new_name = f'doc_{index:03d}{path.suffix}'
8    print(f'{path.name} -> {new_name}')

Run the preview first. Once the mapping looks correct, replace the print with rename.

Avoid Name Collisions

A bulk rename can fail or overwrite files if the destination names already exist.

python
1from pathlib import Path
2
3folder = Path('data')
4for path in folder.iterdir():
5    if path.is_file():
6        target = path.with_name(f'clean_{path.name}')
7        if target.exists():
8            raise FileExistsError(f'{target} already exists')
9        path.rename(target)

This kind of explicit check is important when renaming into a naming scheme that might already be present.

Pattern-Based Renaming

Sometimes you only need a string replacement in each filename.

python
1from pathlib import Path
2
3folder = Path('exports')
4
5for path in folder.glob('*.csv'):
6    new_name = path.name.replace('draft_', 'final_')
7    path.rename(path.with_name(new_name))

This is simple and effective as long as the replacement rule is unambiguous.

Two-Phase Renames Help with Cycles

If one rename would collide with another, a two-phase strategy is safer. First rename everything to temporary names, then rename to the final names.

python
1from pathlib import Path
2
3folder = Path('swap')
4paths = sorted(folder.glob('*.txt'))
5
6temporary = []
7for index, path in enumerate(paths):
8    temp = path.with_name(f'__temp__{index}{path.suffix}')
9    path.rename(temp)
10    temporary.append(temp)
11
12for index, path in enumerate(temporary, start=1):
13    final_name = path.with_name(f'final_{index:03d}{path.suffix}')
14    path.rename(final_name)

This is useful when the final names overlap with names that already exist in the same directory during the rename operation.

os.rename Versus Path.rename

os.rename and Path.rename do the same basic job. pathlib usually reads better because the path manipulation methods are attached to the path object itself.

If you are writing new code, pathlib is often the cleaner default.

Common Pitfalls

  • Renaming files without sorting first when the new names depend on sequence numbers.
  • Running a bulk rename without a dry run and discovering mistakes only after the files changed.
  • Overwriting or colliding with existing filenames because the script never checked the target paths.
  • Applying a broad rename rule to directories when only files should have been changed.
  • Using ambiguous string replacements that accidentally rename the wrong parts of filenames.

Summary

  • Use pathlib for clear and maintainable bulk rename scripts.
  • Sort files before assigning numbered names.
  • Preview the rename mapping before applying it.
  • Check for collisions so you do not overwrite files accidentally.
  • Keep the rename rule narrow and explicit so the batch operation stays predictable.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.