python walk遍历文件_Python os.walk文件遍历

os.walk(top, topdown=True, οnerrοr=None, followlinks=False)

可以得到一个三元tupple(dirpath, dirnames, filenames),

第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。

dirpath 是一个string,代表目录的路径,

dirnames 是一个list,包含了dirpath下所有子目录的名字。

filenames 是一个list,包含了非目录文件的名字。

这些名字不包含路径信息,如果需要得到全路径,需要使用os.path.join(dirpath, name).

通过for循环自动完成递归枚举

a

importosfor i in os.walk('c:'+os.sep+'ant'):print i

输出:

('c:\\ant', ['bin', 'docs', 'etc', 'lib', 'Project'], ['fetch.xml', 'get-m2.xml', 'INSTALL', 'KEYS', 'LICENSE', 'NOTICE', 'README', 'WHATSNEW'])

('c:\\ant\\bin', [], ['ant', 'ant.bat', 'ant.cmd', 'antenv.cmd', 'antRun', 'antRun.bat', 'antRun.pl', 'complete-ant-cmd.pl', 'envset.cmd', 'lcp.bat', 'runant.pl', 'runant.py', 'runrc.cmd'])

('c:\\ant\\docs', ['ant2', 'antlibs', 'images', 'manual', 'projects', 'slides', 'webtest'], ['antnews.html', 'ant_in_anger.html', 'ant_task_guidelines.html', 'appendix_e.pdf', 'breadcrumbs.js', 'bugs.html', 'bylaws.html', 'contributors.html', 'external.html', 'faq.html', 'favicon.ico', 'index.html', 'legal.html', 'LICENSE', 'license.html', 'mail.html', 'mission.html', 'nightlies.html', 'page.css', 'problems.html', 'projects.html', 'resources.html', 'svn.html'])

('c:\\ant\\docs\\ant2', [], ['actionlist.html', 'features.html', 'FunctionalRequirements.html', 'original-specification.html', 'requested-features.html', 'requested-features.txt', 'VFS.txt'])````````````````````````````

遍历文件夹并删除特定格式文件的示例

#!/usr/bin/python#-*- coding: utf-8 -*-

importosdefdel_files(path):for root , dirs, files inos.walk(path):for name infiles:if name.endswith(".tmp"):

os.remove(os.path.join(root, name))print ("Delete File:" +os.path.join(root, name))#test

if __name__ == "__main__":

path= '/tmp'del_files(path)

通过for循环即可完成目录的递归

#!/usr/bin/python#-*- coding: gbk -*-

#os.walk()的使用

importos#枚举dirPath目录下的所有文件

defmain():#begin

fileDir = "F:" + os.sep + "aaa" #查找F:\aaa 目录下

for root, dirs, files inos.walk(fileDir):#begin

for dir indirs:#begin

print(os.path.join(root, dir))#end

for file infiles:#begin

print(os.path.join(root, file))#end

#end

os.system("pause")#end

if __name__ == '__main__':#begin

main()#end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值