【Python】三种遍历文件目录的方法

#coding:utf-8

# 方法1:递归遍历目录

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):    #判断路径是否为文件,如果不是继续遍历
            visitDir(pathname)
        else:
            print pathname

if __name__ == "__main__":
    path = r"/Users/GaoHongxing/Desktop"
visitDir(path)
          
# 方法2:函数递归 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,())


# 方法3: 函数递归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()与os.walk()产生的文件名列表不同:
os.walk() 只产生文件路径
os.path.walk()    产生目录树下的目录路径和文件路径
"""

你可能感兴趣的:(Python)