traverse python print a directory and all files and directories inside

# Depth traversing print a folder 
DEF print_all_dir (dir):
# judge dir is the folder
IF os.path.isdir (dir):
# If it is a folder, the folder to print
Print (dir)
# re-iterate
for next_dir in os.listdir (dir):
# recursive call, clip continues to traverse the printing operation for each file in the folder / file, add the path to the file before
print_all_dir (os.path.join (dir, next_dir))
  # judge dir is the file
elif os.path.isfile (dir):
# direct Print
Print (dir)
  # If neither a folder and not a file, the path does not exist,
the else:
# prompt and the end of the function
print ( "the path % s does not exist, please double-check! "dir%)
return

in general, the path for a first operation to determine whether there is, but once inside the recursive call each will determine whether there is, the efficiency will be relatively low, so the judge put else only need to determine first-entered the path exists can be.

Guess you like

Origin www.cnblogs.com/lynnk1ng/p/12344128.html
Recommended