首页 > 解决方案 > 重命名同一文件夹中的图像(新名称+图像大小)时出现问题

问题描述

这可能是一个简单的问题,但我到处寻找我的问题的答案,但找不到合适的答案。

我想重命名同一个(!)文件夹中的多个图像,并用新的图像名称替换当前图像名称加上添加的图像大小:

示例:“image_1.jpg”(600x300px)到“cat-600x300.jpg”“image_abc.jpg”(1920x1080px)到“cat-1920x1080.jpg”

不幸的是,我的代码正在创建以下错误。 PermissionError: [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用:

代码:

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)

标签: pythonpython-imaging-libraryrenameimage-size

解决方案


可能是因为您正在打开文件以获取其属性,并且在文件打开时您正在请求操作系统重命名文件。

在您的情况下,您可以尝试在重命名之前关闭文件im.close()

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)

推荐阅读