2016-08-22 99 views
-2

我的情況來處理的python文件如何遍歷在Python

我的進程樹結構是這樣

dirctory 
. 
...subdir1 
    . 
    ....sub-sub-dir1 
      . 
      . ..file1 
  1. 首先,我需要在一個目錄中的文件和子目錄進入子目錄1並逐個讀取子子目錄(1到n)並從子子目錄和進程中獲取文件。

  2. 就像這個過程一樣,子子目錄中的所有文件都會返回到子目錄 循環。

  3. 閱讀下一個子目錄並逐個閱讀子子目錄並從子子目錄和進程中獲取文件。

請幫我解決我們如何在Python中完成上述操作。如果我得到快速響應,我會很感激你。

感謝

+0

有很多是有很好的回答類似的問題,嘗試http://stackoverflow.com/questions/5817209/browse-files-and在Python中的子文件夾 – mitoRibo

+2

[使用os.walk()遞歸遍歷Python中的目錄](http://stackoverflow.com/questions/16953842/using-os-walk-to-recursively-traverse -directories-in-python) – sushain97

回答

1

類似的東西:

directory_dict = dict() 

# Create the list of the sub_directories 
dir_list = [sub_path for sub_path in os.listdir(given_path) if os.path.isdir(given_path+'/'+sub_path)] 

# Loop into the list of sub_directories 
for sub_dir in dir_list: 
    # Create an empty dict to store the informations 
    sub_dir_dict = dict() 

    # Create the list of the sub_sub_directories 
    sub_sub_dir_list = [sub_path for sub_path in os.listdir('%s/%s' % (given_path, sub_dir)) if os.path.isdir(given_path+'/'+sub_dir+'/'+sub_path)] 

    # Loop into the sub_sub_directories list 
    for sub_sub_dir in sub_sub_dir_list: 
     # Set current directory to the sub_sub_directory path 
     os.chdir(given_path+'/'+sub_dir+'/'+sub_sub_dir) 
     # Filter files 
     files = [dir_file for dir_file in os.listdir(given_path+'/'+sub_dir+'/'+sub_sub_dir) if os.path.isfile(os.path.join(given_path+'/'+sub_dir+'/'+sub_sub_dir, dir_file))] 

     # Store the list of file into the sub_directory dict at the proper key 
     sub_dir_dict[sub_sub_dir] = files 
    # Store the sub_dir dictionaries into the directory_dict at the proper key 
    directory_dict[sub_dir] = sub_dir_dict 
+0

你應該看看這個:http://stackoverflow.com/a/5817256/4396006 –

+0

我知道這一點,但我有t呃,我還不習慣它,儘管我應該做到這一點,無論如何,謝謝你,這些例子比我迄今爲止看到的更清楚。 – Martin

+0

謝謝馬丁。你的解決方案非常棒。 – Bhaskar