2016-12-09 10 views
0

サブディレクトリ内に格納されているいくつかのファイルの名前を、ベース名の最後の4文字を削除して変更しようとしています。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) 

しかし、今、私はすべてのサブディレクトリに上記を繰り返したいの:私は通常使用して1つのディレクトリ内のファイルを検索し、名前を変更するglob.glob()を使用しています。私は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.walkによって返さtupleの最初の項目は、現在のパスがこれだけのファイル名を指定して、それを組み合わせることos.path.joinを使用しています歩くと同じディレクトリに... –

+0

@RafaelRodrigoDeSouza - ありがとう、あなたはniemmiの答えで説明されている通りです=) – Joseph

答えて

2

ファイルの完全パスをos.renameに渡す必要があります。私はあなたではないので、あなたもos.raname上のファイルのフルパスを渡すべきだと考え

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

関連する問題