您的位置:首页 > 编程语言 > Python开发

Python 用 os.walk 遍历目录

2013-11-06 23:57 591 查看
先看下代码:

import os

for i in os.walk('c:'+os.sep+'ant'):
print i[0]

下面是输出:

c:\ant

c:\ant\bin

c:\ant\docs

c:\ant\docs\ant2

c:\ant\docs\antlibs

c:\ant\docs\antlibs\antunit

c:\ant\docs\antlibs\compress

c:\ant\docs\antlibs\dotnet

c:\ant\docs\antlibs\props

后面还有很长.

如果不使用这个方法,遍历同样能达到效果.不过使用 os.walk 方便很多了.

这个方法返回的是一个三元tupple(dirpath, dirnames, filenames),

其中:

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

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

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

filenames是一个list,包含了非目录文件的名字.这些名字不包含路径信息,如果需要得到全路径,需要使用 os.path.join(dirpath, name).

下面是可以看到 os.walk 方法返回的内容.

代码:

import os

for 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'])
('c:\\ant\\docs\\antlibs', ['antunit', 'compress', 'dotnet', 'props', 'svn'], ['bindownload.cgi', 'bindownload.html', 'charter.html', 'index.html', 'proper.html', 'sandbox.html', 'srcdownload.cgi', 'srcdownload.html'])
('c:\\ant\\docs\\antlibs\\antunit', [], ['index.html'])
('c:\\ant\\docs\\antlibs\\compress', [], ['index.html'])
('c:\\ant\\docs\\antlibs\\dotnet', [], ['index.html'])
('c:\\ant\\docs\\antlibs\\props', [], ['index.html'])
...

当然后面还有很长了.

有了这个函数无论是遍历文件夹,还是遍历文件都很方便.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: