How to rename a file using Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python provides two standard ways to rename files: os.rename() and pathlib.Path.rename(). Both change a file's name or move it to a different directory. os.rename() works with string paths and is available in all Python versions. pathlib.Path.rename() provides an object-oriented interface and is available in Python 3.4+. For moving files across filesystems, use shutil.move() since os.rename() fails when source and destination are on different mount points.
Using os.rename()
os.rename() takes two arguments: the current path and the new path. If the destination already exists, behavior varies by OS — on Unix it silently overwrites, on Windows it raises FileExistsError.
Using pathlib.Path.rename()
Path.rename() returns the new Path object (Python 3.8+). with_name() and with_suffix() create new paths based on the original, making renames more readable.
Using shutil.move()
For moving files across filesystems:
shutil.move() falls back to copy-then-delete when os.rename() fails, making it work across mount points, network drives, and different partitions.
Batch Renaming
Safe Renaming (Avoid Overwrites)
Renaming with Regular Expressions
Error Handling
Common Pitfalls
os.rename()fails across filesystems: On Linux/macOS, moving a file to a different mount point withos.rename()raisesOSError: [Errno 18] Invalid cross-device link. Useshutil.move()which handles cross-filesystem moves by copying then deleting.- Silent overwrite on Unix: On Linux/macOS,
os.rename()silently overwrites the destination if it exists. On Windows, it raisesFileExistsError. CheckPath.exists()before renaming if you want consistent cross-platform behavior. - Not creating the destination directory: Renaming to a path in a non-existent directory raises
FileNotFoundError. Create the directory first withos.makedirs(dir, exist_ok=True)orPath.mkdir(parents=True, exist_ok=True). - Using relative paths in batch operations: When iterating with
glob(), the paths are relative to the glob root. Usingpath.rename('new_name')places the file in the current working directory, not in the file's original directory. Usepath.rename(path.parent / 'new_name')to keep it in the same directory. - Race conditions with existence checks: Checking
if not exists()then renaming has a TOCTOU (time-of-check-to-time-of-use) race condition. Another process may create a file with the same name between the check and the rename. For atomic operations, useos.replace()or handle the exception.
Summary
os.rename(old, new)renames or moves files within the same filesystemPath.rename(new)provides the same functionality with an object-oriented API- Use
Path.with_name()andPath.with_suffix()for clean rename expressions shutil.move()works across filesystems by falling back to copy-then-delete- Check for existing destination files to avoid silent overwrites on Unix
- Use
Path.parent / new_namein batch operations to keep files in their original directory
Related reading
- How to replace certain values in Tensorflow tensor with the values of the other tensor?
- How to replace NaNs by preceding or next values in pandas DataFrame?
- How to replace text in a string column of a Pandas dataframe?
- how to replace values of selected row of a column in panda's dataframe?
- How to replace whitespaces with underscore?
- How to replace yield gen.Taskfn, argument with an equivalent asyncio expression?
- How to represent an infinite number in Python?
- how to represent graphs /trees in python and how to detect cycles?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.