2017-01-16 64 views
3

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

我不確定錯誤的含義或如何解決此問題。有小費嗎?我也很想看看你們中有些人可以採取其他更有效的方式來實現這一目標。

+1

不要忘記先備份; [幾天前某個人](http://stackoverflow.com/q/41637906/1636276)最終失去了所有嘗試對圖像文件執行批量操作的圖像。 – Tagc

+1

我會推薦使用'+'來連接目錄和文件名,而不是使用'os.path.join'函數。此外,如果您仍處於測試階段,也許您不應該修改圖像的實際名稱,而應該在程序中創建它們的副本,然後修改這些副本並適當地刪除副本。錯誤的最可能原因是您使用枕頭打開圖像;嘗試在執行重命名之前關閉此文件 – smac89

+1

可能是因爲您打開了文件'Image.open(images_dir + file)'。無論如何,我沒有看到需要這樣做,只需檢查文件名是以該格式結尾還是分割擴展名並檢查它。 –

回答

4

Image.open()打開圖像並讀取其標題,但仍保持文件打開,因此操作系統無法重命名它。

在重命名之前嘗試del img或嘗試img.load()強制加載數據並釋放圖像文件的保留。

+0

謝謝,那正是問題所在!你的解決方案和@Steven Summers的解決方案都是在使用Image的前提下工作的! – ThatGuy7