change the name of all files in a folder in python

You can use the os module in Python to rename files in a folder. Here's an example code:

main.py
import os

folder_path = "/path/to/folder"

for filename in os.listdir(folder_path):
    # get the current file name and extension
    file_name, file_ext = os.path.splitext(filename)

    # change the file name as per your requirement
    new_file_name = file_name.replace("old_name", "new_name")

    # join the new file name with the extension
    new_filename = new_file_name + file_ext

    # rename the file with the new name
    os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_filename))
524 chars
17 lines

In the above code, we first specify the path to the folder where we want to rename the files. We then loop through all the files using the os.listdir() function. For each file, we split the file name and extension using the os.path.splitext() function.

We then modify the file name as per our requirement using string manipulation, for example, by replacing a certain part of the file name with a new name. We then join the new file name with the extension and rename the file using the os.rename() function by providing the old and new file paths.

gistlibby LogSnag