python重命名多张照片_python-重命名具有连续编号的图像文件目录

我有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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值