2013-12-12 114 views
0

我想重命名文件夾中的所有文件。每個文件名將從「whateverName.whateverExt」更改爲「namepre + i.whateverExt」。例如從 「xxxxx.jpg」 到 「namepre1.jpg」重命名文件名索引

我嘗試從(Rename files in sub directories)的修改代碼,但不能...

import os 

target_dir = "/Users/usename/dirctectory/" 

for path, dirs, files in os.walk(target_dir): 
    for i in range(len(files)): 
     filename, ext = os.path.splitext(files[i]) 
     newname_pre = 'newname_pre' 
     new_file = newname_pre + str(i) + ext 

     old_filepath = os.path.join(path, file) 
     new_filepath = os.path.join(path, new_file) 
     os.rename(old_filepath, new_filepath) 

有人能幫助我嗎? THX !!!

+0

什麼是失敗? –

+0

提示:os.path.join(path,file)'中的'file'是什麼? –

回答

1

試試這個版本:

import os 

target_dir = "/Users/usename/dirctectory/" 

for path, dirs, files in os.walk(target_dir): 
    for i in range(len(files)): 
     filename, ext = os.path.splitext(files[i]) 
     newname_pre = 'newname_pre' 
     new_file = newname_pre + str(i) + ext 

     old_filepath = os.path.join(path, files[i]) # here was the problem 
     new_filepath = os.path.join(path, new_file) 
     os.rename(old_filepath, new_filepath) 
0

你應該更新這個問題,說明你運行這個時得到的輸出。此外,請嘗試打印出每個迭代的值爲new_file,以查看您是否獲得了正確的文件路徑。我的猜測是,這條線:

new_file = newname_pre + str(i) + ext 

...應該這樣說:

new_file = newname_pre + str(i) + '.' + ext 

...或者,在一個稍微更Python語法:

new_file = "%s%i.%s" % (newname_pre, i, ext) 
1

也許你做一些錯誤命名一些變量,嘗試這個:

import os 

target_dir = "/Users/usename/dirctectory/" 
newname_tmpl = 'newname_pre{0}{1}' 

for path, dirs, files in os.walk(target_dir): 
    for i, file in enumerate(files): 
     filename, ext = os.path.splitext(file) 
     new_file = newname_tmpl.format(i, ext) 
     old_filepath = os.path.join(path, file) 
     new_filepath = os.path.join(path, new_file) 
     os.rename(old_filepath, new_filepath) 
+0

期間不應放入: newname_tmpl ='newname_pre {0} {1}' – user2988464

+0

謝謝你指出我。 – smeso