圆月山庄资源网 Design By www.vgjia.com

1.os.popen运行shell列表命令
复制代码 代码如下:
def traverseDirByShell(path):
    for f in os.popen('ls ' + path):
        print f.strip()

2.利用glob模块

glob.glob(path)返回带目录的文件名.通配符和shell相似.path不能包含shell变量.
复制代码 代码如下:
def traverseDirByGlob(path):
    path = os.path.expanduser(path)
    for f in glob(path + '/*'):
        print f.strip()

3.利用os.listdir(推荐)

该方法返回不带根目录的文件名或子目录名
复制代码 代码如下:
def traverseDirByListdir(path):
    path = os.path.expanduser(path)
    for f in os.listdir(path):
        print f.strip()

4.利用os.walk(推荐)

返回一个包含3个项目的元组:当前目录名称,子目录名称,子文件名称
复制代码 代码如下:
def traverseDirByOSWalk(path):
    path = os.path.expanduser(path)
    for (dirname, subdir, subfile) in os.walk(path):
        #print('dirname is %s, subdir is %s, subfile is %s' % (dirname, subdir, subfile))
        print('[' + dirname + ']')
        for f in subfile:
            print(os.path.join(dirname, f))

整合代码:
复制代码 代码如下:
#!/usr/bin/python
import os
from glob import glob


def printSeparator(func):
    def deco(path):
        print("call method %s, result is:" % func.__name__)
        print("-" * 40)
        func(path)
        print("=" * 40)
    return deco

@printSeparator
def traverseDirByShell(path):
    for f in os.popen('ls ' + path):
        print f.strip()

@printSeparator
def traverseDirByGlob(path):
    path = os.path.expanduser(path)
    for f in glob(path + '/*'):
        print f.strip()

@printSeparator
def traverseDirByListdir(path):
    path = os.path.expanduser(path)
    for f in os.listdir(path):
        print f.strip()

@printSeparator
def traverseDirByOSWalk(path):
    path = os.path.expanduser(path)
    for (dirname, subdir, subfile) in os.walk(path):
        #print('dirname is %s, subdir is %s, subfile is %s' % (dirname, subdir, subfile))
        print('[' + dirname + ']')
        for f in subfile:
            print(os.path.join(dirname, f))

if __name__ == '__main__':
    path = r'~/src/py'
    traverseDirByGlob(path)

    traverseDirByGlob(path)

    traverseDirByListdir(path)

    traverseDirByOSWalk(path)

标签:
Python,遍历目录

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com