Search code examples
pythonrename

How to rename images in folder?


I have a folder which contains images. The name is like this :

ID03_013_bmp.rf.1d3821394d2c0b482202e204edde93b1.jpg

I want to rename each image, save 8 first characters and remove the rest. and thank you.


Solution

  • You can use the following script, which uses the os standard library.

    import os
    
    folder_dir = "/your/folder/directory" # Path to your folder
    
    filenames = os.listdir(folder_dir) # List all the files in the folder
    ids = [] # List of the the first 8 characters of your filenames
    
    for file in filenames:
        id = file.split(".")[0][:8]
        ids.append(id) 
        target_name = id + ".jpg" # Define how you want your files to be named, currently based on the first 8 characters
        current_path = os.path.join(folder_dir, file)
        target_path = os.path.join(folder_dir, target_name)
        os.rename(current_path, target_path)