2016-08-16 15 views
0

* .pyファイルを再帰的に処理するためのコードを記述しています。再帰がPythonで動作しないようです

class FileProcessor(object): 

    def convert(self,file_path): 
     if os.path.isdir(file_path): 
      """ If the path is a directory,then process it recursively 
       untill a file is met""" 
      dir_list=os.listdir(file_path) 
      print("Now Processing Directory:",file_path) 

      i=1 

      for temp_dir in dir_list: 
       print(i,":",temp_dir) 
       i=i+1 
       self.convert(temp_dir) 
     else: 
      """ if the path is not a directory""" 
      """ TODO something meaningful """ 

if __name__ == '__main__': 
    tempObj=FileProcessor() 
    tempObj.convert(sys.argv[1]) 

私は、引数としてディレクトリ・パスを持つスクリプトを実行し、それが唯一のディレクトリの最初の層を実行し、行:

self.convert(temp_dir) 

は決して得る思わなかったコードブロックは、以下の通りですと呼ばれる。私はPython 3.5を使用しています。

+3

self.convert(temp_dir) 

を変更する必要があります。 ['os.walk'](https://docs.python.org/3/library/os.html#os.walk) –

答えて

4

再帰はうまくいきますが、temp_dirはディレクトリではないため、制御をスタブelseブロックに渡します。 ifブロックの外側にprint(file_path)を置くと、これが表示されます。

temp_dirは次のディレクトリではなく、その絶対パスの名前です。 "C:/users/adsmith/tmp/folder"はちょうど"folder"になります。 (質問に私のコメントで述べたように)これを行うための標準的な方法はos.walkを使用する

self.convert(os.path.abspath(temp_dir)) 

ですが、ことを取得するにはos.path.abspathを使用してください。 temp_dirとして

class FileProcessor(object): 
    def convert(self, file_path): 
     for root, dirs, files in os.walk(file_path): 
      # if file_path is C:/users/adsmith, then: 
      # root == C:/users/adsmith 
      # dirs is an iterator of each directory in C:/users/adsmith 
      # files is an iterator of each file in C:/users/adsmith 
      # this walks on its own, so your next iteration will be 
      # the next deeper directory in `dirs` 

      for i, d in enumerate(dirs): 
       # this is also preferred to setting a counter var and incrementing 
       print(i, ":", d) 
       # no need to recurse here since os.walk does that itself 
      for fname in files: 
       # do something with the files? I guess? 
+1

ありがとうございます。詳細な説明と素晴らしい例は、多くの助けになります! –

0

のみ親パスなしでファイル名を持っている、あなたがところでこれを行うには良い方法があります

self.convert(os.path.join(file_path, temp_dir)) 
+0

ありがとう、たくさんのPythonの方法で学ぶ –

関連する問題