1

I have been trying my hand at this for a while and I am afraid this will get marked as a duplicate, even though I feel this is not a duplicate to Python list directory, subdirectory, and files. This solution prints it out to the format of path/subdirectory/files. But that is not what I need.

Consider the following structure of my directory:

Root

 - Directory1
    - Files
 - Directory2
    - Files
 - Directory3
    - Subdirectory
        - Sub-subdirectory1
            - Files
        - Sub-subdirectory2
            - Files
        - Sub-subdirectory3
            - Files
 - Directory4
    - Files

For my program, I need the name of the path, which isn’t difficult. However, I also need the name of the subdirectory, which I can do with for name in subdirs, however, I cannot get the name of the files within the subdirectory. This is what I have tried:

for path, subdirs, files in os.walk(root):
    for dirname in subdirs:
        print dirname
        for filename in os.listdir(path + ‘\\’ + dirname):
            print filename

This works until I hit a subdirectory, where it then treats the file names as the subdirectory names. This becomes a problem in my program as it causes it to crash and I am taking information out of the files and converting them into XML files. And I need the directory name in order to properly name the file, and give it the appropriate header.

I want the following output:

 - Directory1
    - Files
 - Directory2
    - Files
 - Sub-subdirectory1
    - Files
 - Sub-subdirectory2
    - Files
 - Sub-subdirectory3
    - Files
 - Directory3
    - Files

How do I go about achieving this?

scharette
  • 9,437
  • 8
  • 33
  • 67
Sailanarmo
  • 1,139
  • 15
  • 41

1 Answers1

2

If you want to print only directories that have files:

for path, subdirs, files in os.walk(root):
    if files:
        print os.path.basename(path)
        for filename in files:
            print '  ' + filename  # spaces are just for indent

If you need empty directories too, remove if files.

Eugene Primako
  • 2,767
  • 9
  • 26
  • 35