Python每日进阶--使用os.walk()方法遍历目录

罗列从某个文件夹下的某一类文件,可以使用通配符*
path:路径
fun:处理函数
suffix:匹配指定规则的文件

#coding=utf-8

# 利用os.walk()方法遍历目录

import os
import fnmatch
import time

path = '../src'
for root, dirs, files in os.walk(path):
    for file in files:
        suffix = os.path.splitext(file)[1]
        if '.py' == suffix:
            filepath = os.path.join(root, file)
            print( filepath)

def listFile(path, fun, suffix='*'):
    for  root, dirs, files in os.walk(path):
        for file in files:
            if fnmatch.fnmatch(file, suffix):
                fun(os.path.join(root, file))

def  function(filepath):
    stime =time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getmtime(filepath)))
    print(filepath+'=>'+stime)
listFile('../src/', function, '*.py')

猜你喜欢

转载自blog.csdn.net/webofrxy/article/details/80431361