Sometimes, we want to rename multiple files in a directory in Python.
In this article, we’ll look at how to rename multiple files in a directory in Python.
How to rename multiple files in a directory in Python?
To rename multiple files in a directory in Python, we can loop through the files and call os.rename
on them.
For instance, we write
import os
for filename in os.listdir("."):
if filename.startswith("cheese_"):
os.rename(filename, filename[7:])
to get the list of files in a directory with os.listdir
.
And then we check if the filename
string starts with 'cheese_'
with startswith
.
If it’s True
, then we call os.rename
to rename filename
to the same name without the 'cheese_
part.
Conclusion
To rename multiple files in a directory in Python, we can loop through the files and call os.rename
on them.