python - 重命名同一文件夹中的图像(新名称+图像大小)时出现问题
问题描述
这可能是一个简单的问题,但我到处寻找我的问题的答案,但找不到合适的答案。
我想重命名同一个(!)文件夹中的多个图像,并用新的图像名称替换当前图像名称加上添加的图像大小:
示例:“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)
解决方案
可能是因为您正在打开文件以获取其属性,并且在文件打开时您正在请求操作系统重命名文件。
在您的情况下,您可以尝试在重命名之前关闭文件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)
推荐阅读
- java - SwipeRefreshLayout 不适用于空列表
- postgresql - 将数据目录从根硬盘移动到另一个硬盘后如何修复postgresql的连接?
- python - matplotlib 中的某一行未可视化
- javascript - 如何使用网络音频 api 获取原始 pcm 音频?
- swift - 通过 Alamofire 集成salesforce api?
- php - 遇到未捕获的异常类型:ImagickException 消息:无法读取 Codeigniter 中的文件
- c - 您是否需要在 C 枚举的最后一个成员之后添加额外的“,”?
- python - 如何将数据框列更改为字符串
- ios - Alamofire.framework:2个iOS应用程序中的未知错误-1 = ffffffffffffffff
- sqlite - 需要一般 Sqlite 外键解释