Rename all files in a directory with Python

Rename files, why?

I often had the need to change the file name in a folder for different reasons. So, I won’t list the cases in which you could have the necessity to do it, because if you are here, you’ll probably need to do it yet, so let’s dive into code, with examples first.

Changing all files names to lower case.

In this code we will make all the character to lower case.

import os

first = os.listdir()

for file in os.listdir():
    # if you do not want to change the name of the .py file too uncomment the next line
    # if not file.endswith(".py") # and indent the next one (of four spaces)
    os.rename(file, file.lower()) # use upper() for the opposite goal

then = os.listdir()

print("Done, all files to lower case")
for file, file2 in zip(first, then):
    print(file, "-", file2)

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.