2012-08-19 146 views
0

我在目錄中有400個文件(使用.png擴展名)。他們以005.png這個名字開頭,然後上升到395.png重命名目錄中的文件

我想用os.rename重命名它們:

os.rename(006.png,005.png) 

換句話說,我希望所有的數字向下移動一個,文件005.png重命名爲004.png和重命名395.png394.png,等等。

我不想手動做到這一點,因爲這會花費太長的時間:

os.rename(005.png,004.png) 
os.rename(006.png,005.png) 
... 

我怎麼能這樣簡單?我正在使用S60第二版FP3。

在此先感謝!

+4

「請給我一碼」 - 我們不這樣做,在這裏。向我們展示您嘗試過的方式以及遇到問題的位置,我們會盡力提供幫助。我們不會爲您編寫代碼。 – msw 2012-08-19 13:57:37

回答

3

你可以使用一個簡單的循環:

for i in xrange(4, 396): 
    os.rename(str(i).zfill(3) + ".png", str(i-1).zfill(3) + ".png")) 

,並僅此而已:)

2

環路確實是最容易的。作爲一種替代str(i).zfill(3) + ".png",你可以使用

template = "{0:03d}.png" 
for i in range(4, 396): 
    os.rename(template.format(i), template.format(i-1)) 
1
import os 
path = r"C:\your_dir"#i've added r for skipping slash , case you are in windows 
os.chdir(path)#well here were the problem , before edit you were in different directory and you want edit file which is in another directory , so you have to change your directory to the same path you wanted to change some of it's file 
files = os.listdir(path) 
for file in files: 
    name,ext = file.split('.') 
    edited_name=str(int(name)-1) 
    os.rename(file,edited_name+'.'+ext) 

希望這是你在找什麼彌補

+0

我嘗試你的代碼和python說的 「os.rename(file,newName) TypeError:強制轉換爲Unicode:需要字符串或緩衝區,int找到 >>>」 – 2012-08-20 11:15:36

+0

感謝您告訴我,我編輯瞭解決方案: ) – Hamoudaq 2012-08-21 00:00:10

+0

Sir ......它說 >>> ===== RESTART ===== >>> 回溯(最近一次通話的最後一次): run_click文件「ped.py」,行1061 File 「D:\ Ped.temp \ Unnamed1.py」,第7行,在? os.rename(「file」,「newName」) OSError:[Errno 2]沒有這樣的文件或目錄 >>> 爲什麼? 我把確切的文件路徑! – 2012-08-21 13:04:48

相關問題