我有900个图像文件(所有png,jpg或gif)。我试图写一个快速代码,将每个图像文件并将其重命名为1-900的数字(顺序无关紧要,只是它们每个都是唯一的)。我尝试低于:重命名连续编号的图像文件目录
renamer.py
"""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
os.rename(images_dir + file, images_dir + str(file_name) + ".png")
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
Process finished with exit code 1
我不确定错误的含义或如何解决此问题。有小费吗?我也很想看看你们中有些人可以采取其他更有效的方式来实现这一目标。
不要忘记先备份; [几天前某个人](http://stackoverflow.com/q/41637906/1636276)最终失去了所有尝试对图像文件执行批量操作的图像。 – Tagc
我会推荐使用'+'来连接目录和文件名,而不是使用'os.path.join'函数。此外,如果您仍处于测试阶段,也许您不应该修改图像的实际名称,而应该在程序中创建它们的副本,然后修改这些副本并适当地删除副本。错误的最可能原因是您使用枕头打开图像;尝试在执行重命名之前关闭此文件 – smac89
可能是因为您打开了文件'Image.open(images_dir + file)'。无论如何,我没有看到需要这样做,只需检查文件名是以该格式结尾还是分割扩展名并检查它。 –