This article summarizes Python's way of traversing a directory. Share to everyone for your reference, as follows:
Method one uses recursion:
"" "Def Walkdir (dir, dir_callback = none, File_callback = none): For item in Os.listdir (dir): print item; FullPath = dir + os.sep + item if Os.path.isdir (fullpath): walkdir (FullPath, Dir_callback, File_callback) If Dir_callback:dir_callback (FullPath) else: if File_callback:file_callback (fullpath) "" "Def Deletedir (dir ): print "path" #os. RmDir (dir) def deletefile (file): try: print "file" #os. Unlink (file) except Windowserror, E: passwalkdir (os.environ[' TEMP '], Deletedir, DeleteFile)
Method Two:
Import OS, Statdef Walkdir (dir, dir_callback = none, File_callback = none): for Root, dirs, files in Os.walk (dir):
for f in Files: print f file_path = Os.path.join (root, f) if File_callback:file_callback (file_path)
for d in dirs: Dir_path = Os.path.join (root, D) if Dir_callback:dir_callback (Dir_path) def deletedir (dir):
print "path" #os. RmDir (dir) def deletefile (file): try: print "file" #os. Unlink (file) Except Windowserror, E: passwalkdir (os.environ[' TEMP '], Deletedir, DeleteFile)
More interested in Python related content readers can view this site topic: "Python data structure and algorithm tutorial", "Python Socket Programming Skills Summary", "Python function Tips Summary", "Python string manipulation Skills summary", " Python Introductory and Advanced Classic tutorials and Python file and directory Operations Tips Summary
I hope this article is helpful for Python program design.