-2

I have scenario to process the files in python

my process tree structure is like

dirctory
.
...subdir1
     .
     ....sub-sub-dir1
           .
           . ..file1
  1. First I need to go the subdir1 and read one by one sub-sub-dirs (1 to n) and get the file from the sub-sub-dir and process.

  2. Like this process all the files in sub-sub-dirs then go back to the sub-dir loop.

  3. Read next subdir and read the one by one sub-sub-dirs and get the file from the sub-sub-dir and process.

Please, help me out how can we do the above in Python. I would be grateful to you if I get a quick response.

Thanks

Pj_
  • 824
  • 6
  • 15
Bhaskar
  • 271
  • 7
  • 20
  • there are a lot of similar questions that have really good answers, try http://stackoverflow.com/questions/5817209/browse-files-and-subfolders-in-python for example – mitoRibo Aug 22 '16 at 23:00
  • 2
    Possible duplicate of [Using os.walk() to recursively traverse directories in Python](http://stackoverflow.com/questions/16953842/using-os-walk-to-recursively-traverse-directories-in-python) – sushain97 Aug 22 '16 at 23:01

1 Answers1

1

Something like that:

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
Martin
  • 105
  • 1
  • 10
  • 1
    You should really look at this: http://stackoverflow.com/a/5817256/4396006 –  Aug 22 '16 at 23:24
  • I knew this but I have to say, I'm not used to it yet, even though I should get to it, anyway, thank you for that, those examples are clearer than the one I saw until now. – Martin Aug 23 '16 at 01:32
  • 1
    Thanks Martin. you solution is awesome. – Bhaskar Aug 24 '16 at 10:10