Categories
Python Answers

How to rename multiple files in a directory in Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *