Python three methods to traverse the file directory instance code

  • 2020-07-21 08:47:17
  • OfStack

The example code in this paper mainly realizes the operation of python traversing the file directory, with three methods. The specific code is as follows.


#coding:utf-8 
 
#  methods 1 : Recursively traverses the directory  
 
import os 
def visitDir(path): 
  li = os.listdir(path) 
  for p in li: 
    pathname = os.path.join(path,p) 
    if not os.path.isfile(pathname):  # Determines whether the path is a file, if not to continue traversal  
      visitDir(pathname) 
    else: 
      print pathname 
 
if __name__ == "__main__": 
  path = r"/Users/GaoHongxing/Desktop" 
visitDir(path) 
      
#  methods 2 : Function recursion  os.path.walk() 
 
import os, os.path 
 
def visitDir(arg, dirname, names): 
  for filepath in names: 
    print os.path.join(dirname, filepath) 
     
if __name__ == "__main__": 
  path = r"/Users/GaoHongxing/Desktop" 
  os.path.walk(path,visitDir,()) 
 
 
#  methods 3 :   Function recursive os.walk() 
import os 
 
def visitDir(path): 
  for root, dirs, files in os.walk(path): 
    for filepath in files: 
      print os.path.join(root, filepath) 
       
if __name__ == "__main__": 
  path = r"/Users/GaoHongxing/Desktop"  
  visitDir(path)  
 
""" 
os.path.walk() with os.walk() The resulting list of filenames is different:  
os.walk()  Only the file path is generated  
os.path.walk()   Generates the directory path and file path under the directory tree  
""" 

conclusion

That's the end of this article on Python3 method traversal file directory example code, I hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: