2016-08-22 69 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