How to rename files in Python
Learn different ways to rename files in Python using the os and pathlib modules.
Learn different ways to rename files in Python using the os and pathlib modules.
Rename files with os
¶
You can use
os.rename(old_name, new_name)
For example we can combine it with os.path.splitext()
to get the base name and file extension, and then combine it to a new name:
import os
for file in os.listdir():
name, ext = os.path.splitext(file)
new_name = f"{name}_new{ext}"
os.rename(file, new_name)
Rename files with pathlib
¶
The same could be achieved with the pathlib module and
Path.rename(new_name)
With a Path object we can access .stem
and .suffix
:
from pathlib import Path
for file in os.listdir():
f = Path(file)
new_name = f"{f.stem}_new{f.suffix}"
f.rename(new_name)
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
* This is an affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏