前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python的os遍历

python的os遍历

作者头像
py3study
发布2020-01-14 11:07:36
5650
发布2020-01-14 11:07:36
举报
文章被收录于专栏:python3python3

使用python遍历目录用到

方法一:

os.path.walk(top, func, arg)

模块方法,该方法需要输入3个参数:

top为起始路径, 

func为回调函数(可以对遍历出的目录文件做处理),

arg为回调函数func的参数。

见下例子:

代码语言:javascript
复制
#!/usr/bin/env python
import os
import time

#定义一个回调函数,实现找出路径下所有访问时间大于3天的文件
def filter_file(arg, dirname, files):#回调函数的3个参数,arg,walk后查找的dirname, filename
    for f in files:
        file_path = os.path.join(dirname, f)
        if os.path.isfile(file_path): #判断是否为文件,是则继续
            if time.time() - os.path.getatime(file_path) > arg:#当前时间和文件的访问时间差大于3天则打印
                print file_path

#'/root'为起始路径
#filter_file为回调函数
#259200为回调函数的参数,是3天的秒数    
os.path.walk('/root', filter_file, (259200))

方法二:

使用os.walk

os.walk(top) 此方法默认只需要输入起始路径参数,它会返回一个迭代的对象,迭代出来是一个元组对象,里面有3个数据,第一个起始路径下的目录,第二个是这个目录下的所有目录列表,如果没有则是空列表,第三个是这个目录下所有的文件列表,如果没有则为空。

来看例子:

代码语言:javascript
复制
#!/usr/bin/env python
import os
for item in os.walk('test'):
    print item

输出:

代码语言:javascript
复制
('test', ['case8', 'case2', 'case1', 'case6'], ['downloadimg.py', 'wrapper.py', '1024.py'])
('test/case8', ['files1', 'files2'], ['simple_node.py', 'server.py', 'server.pyc', 'client.py'])
('test/case8/files1', [], ['test.txt'])
('test/case8/files2', [], ['test.txt'])
('test/case2', [], ['website.xml', 'handler.py'])
('test/case1', [], ['utils.py', 'text', 'rules.py', 'rules.pyc', 'handlers.py', 'utils.pyc', 'markup.py', 'test_output.html', 'handlers.pyc'])
('test/case6', [], ['simple_edit.dat', 'simple_edit.cgi'])

可以看出迭代出许多元组,每一元组第一个元素是test目录下的所有目录,第二个目录列表是第一个目录元素下的所有目录,没有的是空列表,第三个文件列表是第一个目录元素下的所有文件。

我们使用循环打印出文件:

代码语言:javascript
复制
#!/usr/bin/env python
import os
for dirpath, dirnames, filenames in os.walk('test'):
    if filenames:
        for f in filenames:
            print os.path.join(dirpath, f)

输出:

代码语言:javascript
复制
test/downloadimg.py
test/wrapper.py
test/1024.py
test/case8/simple_node.py
test/case8/server.py
test/case8/server.pyc
test/case8/client.py
test/case8/files1/test.txt
test/case8/files2/test.txt
test/case2/website.xml
test/case2/handler.py
test/case1/utils.py
test/case1/text
test/case1/rules.py
test/case1/rules.pyc
test/case1/handlers.py
test/case1/utils.pyc
test/case1/markup.py
test/case1/test_output.html
test/case1/handlers.pyc
test/case6/simple_edit.dat
test/case6/simple_edit.cgi

这两种方法可以根据需求选择。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档