Renaming files in Python

This is simple demonstration on how to rename files in python. We will be using the in-built  functions os.walk() to list a directory content and os.rename() to do the actual renaming.  

For this demonstration, renaming will involve changing filenames into lowercase and replacing white spaces and dashes with an underscore character.

def rename_files(): 
    #this will list current directory content
    for dirpath, dirnames, filenames in os.walk("."):
        for file in filenames:
            # replace white spaces and dashes with underscore and convert to lower case
            newfilename = file.replace("-", "_")
            newfilename = newfilename.replace(" ", "_").lower()
            os.rename(os.path.join(dirpath, file), os.path.join(dirpath, newfilename))

To exclude files from renaming we can add a simple check that skips certain files based on their names or extensions.

#filters
exclude_suffix = ('.py', '.exe')
exclude_prefix = ('system', 'pycharm')

def rename_files_with_filter():
    for dirpath, dirnames, filenames in os.walk("."):
        for file in filenames:
            #checks if files can be renamed
            if file.endswith(exclude_suffix) or file.startswith(exclude_prefix):
                continue
            #replace white spaces and dashes with underscore and convert to lower case
            newfilename = file.replace("-", "_")
            newfilename = newfilename.replace(" ", "_").lower()
            os.rename(os.path.join(dirpath, file), os.path.join(dirpath, newfilename))

Leave a Reply

Close Menu