-1

I have a directory which holds many sub-directory and inside each sub-directory i have some more sub-sub-directory.

enter image description here

I have a python code which prints and writes the directory and subdirectory in a file. The code :

import os
file = open("list", "w")
for root, dirs, files in os.walk("./customers/"):
   print root
   file.write(root+"\n")

This outputs as :

./customers/A
./customers/A1
./customers/A2
./customers/B
./customers/B1
./customers/B2
./customers/C
./customers/C1
./customers/C2

I just want :

./customers/A1
./customers/A2
./customers/B1
./customers/B2
./customers/C1
./customers/C2

1 Answers1

0

You seem reluctant to update your question to make clear what you want, so I will make a guess that you want only the leaf directories. You can do that like this:

import os

with open('list', 'w') as outfile:
    for root, dirs, files in os.walk("./customers/"):
        if not dirs:    # if root has no sub-directories it's a leaf
            print root
            outfile.write(root+"\n")

For your directory structure this should output:

./customers/C/C2
./customers/C/C1
./customers/B/B2
./customers/B/B1
./customers/A/A2
./customers/A/A1

which looks like it might be what you want.

If you want the output sorted you could write a generator function and sort its output:

import os

def find_leaf_directories(top):
    for root, dirs, files in os.walk(top):
        if not dirs:    # if root has no sub-directories it's a leaf
            yield root

with open('list', 'w') as outfile:
    for dir in sorted(find_leaf_directories('./customers/')):
        print dir
        outfile.write(dir+"\n")

Which will output:

./customers/A/A1
./customers/A/A2
./customers/B/B1
./customers/B/B2
./customers/C/C1
./customers/C/C2
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • lol yeah .. but i want to know one more thing... what to do if i just want to print parent directory , i.e A, B ,C –  Feb 11 '16 at 10:53
  • This will give you the first level of subdirectories: `root, dirs, files = next(os.walk("./customers/")); print dirs` – mhawke Feb 11 '16 at 11:24