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.