2015-12-04 46 views
0

我有一些圖像文件存儲爲0.png,1.png,...,x.png在一個文件夾中。我必須以相反的順序重新命名,即0-> x,1->(x-1),...,(x-1) - > 1,x-> 0。我已經在python中編寫了下面的代碼。「OSError:[Errno 2]沒有這樣的文件或目錄」遇到os.rename

for filename in os.listdir("."): 
    tempname = "t" + filename 
    os.rename(filename, tempname) 
for x in range(minx, maxx+1): 
    tempname = "t" + str(x) + ".png" 
    newname = str(maxx-x) + ".png" 
    os.rename(tempname, newname) 

我遇到以下錯誤:

OSError: [Errno 2] No such file or directory 

我在做什麼錯? 有沒有更智能的方法呢?

+1

也許在中間的一個文件丟失。您應該捕獲「OSError」並將其與受影響的文件名一起打印出來。 – glglgl

+0

我只用兩個文件就試過了,當調用os.rename時它失敗。 – nirupma

+0

嘗試使用'os.path.exists'來檢查您的文件是否存在 –

回答

2

請嘗試以下操作,它使用glob模塊獲取文件列表。這應該包括完整路徑,否則os.rename可能失敗:

import glob 
import os 

source_files = glob.glob(r'myfolder\mytestdir\*') 
temp_files = ['{}.temp'.format(file) for file in source_files] 
target_files = source_files[::-1] 

for source, temp in zip(source_files, temp_files): 
    os.rename(source, temp) 

for temp, target in zip(temp_files, target_files): 
    os.rename(temp, target) 

注意,如果你想針對剛.png文件,你可以改變水珠線爲*.png

+0

感謝martin !!! – nirupma

+0

@Martin ..「os.rename」需要一個完整的路徑名嗎? –

+1

不,但強烈建議使用一個,否則您依賴當前目錄。 –

相關問題