目录遍历的三种方法

1、目录的遍历:递归函数
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)
             

visitDir('C:\\Users\\Administrator\\Desktop\\python_lianxi\\learning\\study')

2、目录的遍历:os.path.walk()

声明:
walk(top,func,arg)

参数top表示需要遍历的目录树的路径

参数func表示回调函数,对遍历路径进行处理。所谓回调函数,是作为某个函数的参数使用,当某个时间触发时,程序调用定义好的回调函数处理某个任务,回调函数必须提供三个参数,
第一个参数位walk()的参数arg,第二个参数为目录列表,第三个参数表示文件列表

参数arg是传递给回调函数的 的元祖,可以是空元组

import os.path
def visitDir_one(arg,dirnames,names):
    for filename in names:
        print(os.path.join(dirnames,filename))
        
os.path.walk('C:\\Users\\Administrator\\Desktop\\python_lianxi\\learning\\study',visitDir_one,())


    

3、目录的遍历:os.walk()
os模块也提供来了walk()用于目录的遍历,类似与os.path.walk()。但效果更高
而且不需要回调函数,更易使用
声明:
walk(top,topdown=True,οnerrοr=None)

参数top标书需要遍历的目录树的路径

参数topdown默认值是True,表示首先返回目录树下的文件,然后在遍历目录树下的子目录,参数topdown值是False,则表示先遍历目录树下的子目录,返回子目录下的文件,然后返回根目录下的文件

参数onerror的默认值是None,表示忽略文件遍历时产生的错误,如果不为空,需要提供一个自定义的函数表示错误信息后继续遍历或者抛出异常后终止遍历

该函数返回一个元组,该元组有3个元素,这3个元素分别是每次遍历的路径名,目录列表。和文件列表

for dirname,pathname,filenames in os.walk('C:\\Users\\Administrator\\Desktop\\python_lianxi\\learning\\study'):
    print(dirname)
    print(pathname)
    for filename in filenames:
        print(os.path.join(dirname,filename))



       
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值