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

Python之文件目录遍历实例代码

2012-12-13 07:59 801 查看
Python之文件目录遍历实例代码
2010-09-25 08:39:30 我来说两句
收藏

我要投稿

Python之文件目录遍历实例代码如下:

import os, sys
from stat import *

def walktree(top, callback):
recursively descend the directory tree rooted at top,
calling the callback function for each regular file

for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode):
Its a directory, recurse into it
walktree(pathname, callback)
elif S_ISREG(mode):
Its a file, call the callback function
callback(pathname)
else:
Unknown file type, print a message
print Skipping %s % pathname

def visitfile(file):
print visiting, file

if __name__ == __main__:
walktree(sys.argv[1], visitfile)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: