2016-08-16 86 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

有一個更好的方式來BTW做到這一點。 ['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.path.abspath吃出

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

雖然規範的方式做到這一點(在我對這個問題發表評論時提及)是使用os.walk

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

由於temp_dir有文件名只無父路徑,你應該改變

self.convert(temp_dir) 

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

感謝,很多學習python的方式 –