如何遍历python中

时间:2016-08-22 22:49:45

标签: python python-2.7

我有在python中处理文件的场景

我的流程树结构就像

dirctory
.
...subdir1
     .
     ....sub-sub-dir1
           .
           . ..file1
  1. 首先,我需要转到subdir1并逐个读取子子目录(1到n)并从子子目录中获取文件并进行处理。

  2. 像这个过程一样,子子目录中的所有文件都会返回子目录 循环。

  3. 读取下一个子目录并逐个读取子目录,并从子子目录中获取文件并进行处理。

  4. 请帮助我如何在Python中完成上述操作。如果我得到快速回复,我将不胜感激。

    由于

1 个答案:

答案 0 :(得分: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