Search code examples
pythonpython-imaging-libraryrenameimage-size

Problem while renaming images (new name + image size) in the same folder


This might be a simple problem, but I have looked for answers to my question everywhere and couldn't find the right one.

I would like to rename multiple images in the same (!) folder and replace current image names with a new one plus added image size:

Examples: 'image_1.jpg' (600x300px) to 'cat-600x300.jpg' 'image_abc.jpg' (1920x1080px) to 'cat-1920x1080.jpg'

Unfortunately, my code is creating the following error. PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:

Code:

from os import listdir
from PIL import Image

newname = "newimage_name"  # this will be the new image name across all images in the same folder. 

for oldfilename in os.listdir():
    im = Image.open(oldfilename)
    w, h = im.size
    file_name, file_ext = oldfilename.split('.')  
    new_name = '{}-{}x{}.{}'.format(newname, w,h, file_ext)
    os.rename(oldfilename, new_name)

Solution

  • Maybe because you are opening the file to get its attributes and while the file is open you are requesting the os to rename the file.

    You can try closing the file prior to renaming with im.close() in your case.

    from os import listdir
    from PIL import Image
    
    newname = "newimage_name"  # this will be the new image name across all images in the same folder. 
    
    for oldfilename in os.listdir():
        im = Image.open(oldfilename)
        w, h = im.size
        file_name, file_ext = oldfilename.split('.')  
        new_name = '{}-{}x{}.{}'.format(newname, w,h, file_ext)
        #CLOSE THE FILE
        im.close()
        os.rename(oldfilename, new_name)