A summary of how Python iterates through the directory

Source: Internet
Author: User
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.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.