我有900个图像文件(所有png,jpg或gif).我正在尝试编写一个快速代码,该代码将获取每个图像文件并将其重命名为1-900中的数字(顺序无关紧要,因为它们每个都是唯一的).我的尝试如下:
重命名器
"""Rename directory of image files with consecutive numbers"""
#Importing - os to make array of files and rename, Image to check file type
import os
from PIL import Image
#Variables for script
images_dir = "C:\file\directory\pictures\\temp\\"
file_array = os.listdir(images_dir)
file_name = 1
#Loops through each file and renames it to either a png or gif file
for file in file_array:
img = Image.open(images_dir + file)
if img.format != "GIF":
os.rename(images_dir + file, images_dir + str(file_name) + ".png")
elif img.format == "GIF":
os.rename(images_dir + file, images_dir + str(file_name) + ".gif")
file_name = file_name + 1
到目前为止,这根本不起作用.我之前曾尝试过其他方法-实际上是使用PIL中的Image打开文件,将其保存为所需的名称,然后删除原始文件-但是那总是会在700左右失败,所以我选择了这种方法.无论如何,它似乎更有效率.我正在使用PyCharm,收到的错误是:
C:\Python27\python.exe “renamer.py”
Traceback (most recent call last):
File “renamer.py”, line 15, in
06001
WindowsError: [Error 32] The process cannot access the file because it
is being used by another process
Process finished with exit code 1
我不确定错误的含义或如何从此处进行故障排除.有小费吗?我也很乐意看到你们中有些人可以提出其他/更有效的方法来做到这一点.
解决方法:
Image.open()打开图像并读取其标题,但仍保留打开的文件,因此操作系统无法重命名它.
重命名之前请尝试del img,或者尝试img.load()强制加载数据并释放图像文件的保留权.
标签:python
来源: https://codeday.me/bug/20191026/1935799.html