2016-12-09 204 views
0

我想通過刪除基本名稱中的最後四個字符來重命名存儲在子目錄中的一些文件。我通常使用glob.glob()查找和使用一個目錄重命名文件:如何使用os.walk()重命名文件?

import glob, os 

for file in glob.glob("C:/Users/username/Desktop/Original data/" + "*.*"): 
    pieces = list(os.path.splitext(file)) 
    pieces[0] = pieces[0][:-4] 
    newFile = "".join(pieces)  
    os.rename(file,newFile) 

但現在我想重複上面的所有子目錄中。我嘗試使用os.walk()

import os 

for subdir, dirs, files in os.walk("C:/Users/username/Desktop/Original data/"): 
    for file in files: 
     pieces = list(os.path.splitext(file)) 
     pieces[0] = pieces[0][:-4] 
     newFile = "".join(pieces)  
     # print "Original filename: " + file, " || New filename: " + newFile 
     os.rename(file,newFile) 

print說法正確打印原來和我正在尋找新的文件名,但os.rename(file,newFile)返回以下錯誤:

Traceback (most recent call last): 
    File "<input>", line 7, in <module> 
WindowsError: [Error 2] The system cannot find the file specified 

我怎麼能解決這個?

+1

我相信你應該在os.raname傳遞文件的完整路徑,也因爲你的不在與步行相同的目錄... –

+0

@RafaelRodrigoDeSouza - 謝謝,你是正確的描述niemmi的答案=) – Joseph

回答

2

您必須將文件的完整路徑傳遞到os.rename。通過os.walk返回tuple的第一個項目是當前路徑,只是用os.path.join將其與文件名結合:

import os 

for path, dirs, files in os.walk("./data"): 
    for file in files: 
     pieces = list(os.path.splitext(file)) 
     pieces[0] = pieces[0][:-4] 
     newFile = "".join(pieces) 
     os.rename(os.path.join(path, file), os.path.join(path, newFile)) 
+0

完美!謝謝您的回答 :) – Joseph