【发布时间】:2017-01-16 16:21:17
【问题描述】:
我有 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(最近一次调用最后一次):
文件“renamer.py”,第 15 行,在
os.rename(images_dir + file, images_dir + str(file_name) + ".png")WindowsError: [错误 32] 进程无法访问该文件,因为它 正在被另一个进程使用
进程以退出代码 1 结束
我不确定错误的含义或如何从此处进行故障排除。有小费吗?我也很想看看你们中的一些人能想出什么其他/更有效的方法来做到这一点。
【问题讨论】:
-
别忘了先备份; some guy a few days ago 最终丢失了他试图对图像文件执行批量操作的所有图像。
-
我建议您使用
os.path.join函数,而不是使用+连接目录和文件名。此外,如果您仍处于测试阶段,也许您不应该修改图像的实际名称,而应该在程序中创建它们的副本,然后修改这些副本并适当地删除这些副本。最可能的错误原因是您使用枕头打开图像;在执行重命名之前尝试关闭此文件 -
可能是您打开了文件
Image.open(images_dir + file)。反正我认为没有必要这样做,只需检查文件名是否以该格式结尾或拆分扩展名并检查它。 -
感谢您的警告!我确实将文件安全地复制到一个临时文件夹中,而我却在玩弄它们。
-
@StevenSummers 虽然图像可能是 gif 或 png 文件,但没有使用这些扩展名保存。也许这是 OP 正在考虑的一个案例。
标签: python