list files in dir tree by recursion import sysos def mylister(currdir)print('[currdir ']'for file in os listdir(currdir)path os path join(currdirfileif not os path isdir(path)print(pathelsemylister(pathif __name__ ='__main__'mylister(sys argv[ ]list files here add dir path back recur into subdirs dir name in cmdline as usualthis file can be both imported and called or run as scriptthough the fact that its result is printed text makes it less useful as an imported component unless its output stream is captured by another program when run as scriptthis file' output is equivalent to that of example - but not identical--unlike the os walk versionour recursive walker here doesn' order the walk to visit files before stepping into subdirectories it could by looping through the filenames list twice (selecting files first)but as codedthe order is dependent on os list dir results for most use casesthe walk order would be irrelevantc:\pp \system\filetoolspython lister_recur py :\temp\test [ :\temp\test[ :\temp\test\partsc:\temp\test\parts\part :\temp\test\parts\part :\temp\test\parts\part :\temp\test\parts\part :\temp\test\random bin :\temp\test\spam txt :\temp\test\temp bin :\temp\test\temp txt we'll make better use of most of this section' techniques in later examples in and in this book at large for examplescripts for copying and comparing directory trees use the tree-walker techniques introduced here watch for these tools in action along the way we'll also code find utility in that combines the tree traversal of os walk with the filename pattern expansion of glob glob handling unicode filenames in xlistdirwalkglob because all normal strings are unicode in python xthe directory and file names generated by os listdiros walkand glob glob so far in this are technically unicode strings this can have some ramifications if your directories contain unusual names that might not decode properly file and directory tools