Question

I have this directory structure:

test1
   file1.txt
   test2
       file2.txt
       test3
           file3.txt
           test4
                file4.txt

my current code to print this directory levels is as follows:

    import os
    def printRootStructure(dirname,indent=0):
        for i in range(indent):
            print "   ",
        print dirname
        if os.path.isdir(dirname):
            for files in os.listdir(dirname):
                printRootStructure(files,indent+1)


    printRootStructure("test")

It currently prints as

test
    file1.txt
    test1

It is not proceeding to next level. any help here to troubleshoot?

Was it helpful?

Solution 2

I think you can fix this by passing the full path name into printRootStructure:

import os
def printRootStructure(dirname,indent=0):
    for i in range(indent):
        print "   ",
    print os.path.basename(dirname) # changed
    if os.path.isdir(dirname):
        for files in os.listdir(dirname):
            printRootStructure(os.path.join(dirname,files),indent+1) # changed

As it was in your original code, you were passing just the last part (this is called the "basename") of each file into printRootStructure when you made the recursive calls.

Working directory and path names

Any time you start up a program on a modern computer, your program runs in a fixed location in the filesystem (this is called the "current working directory"). If you invoke a program from the commane-line, the current working directory is simply the path where you invoked the program's name. If you invoke a program by clicking something in a GUI environment, it can get more complicated, but the general behavior is the same: your program always runs in a specific working directory.

All path tests, and in particular os.path.isdir, are evaluated with respect to that working directory. So when you make your first recursive call in your example, you are testing os.path.isdir("test1"), which doesn't exist in the working directory -- it only exists inside "test" !

The fix is to pass the full path name into your recursive calls. Then, because your full name might be excessive when you print out the tree, I added a call to os.path.basename to print just the basename portion of each file.

OTHER TIPS

Unless you have a specific reason to use recursion, it's simpler to use os.walk to traverse a directory structure.

import os
import os.path as P
for topdir, subdirs, files in os.walk(starting_point):
  print "    " * topdir.count(P.sep), P.basename(topdir)
  for f in sorted(files):
    print "    " * (topdir.count(P.sep) + 1), f
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top