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)

代码节选自codego.net

转载于:https://blog.51cto.com/qianc81115/1631761

Python遍历目录的4种方法相关推荐

  1. python遍历数组的两种方法及将print的内容写入文件中

    python遍历数组的两种方法 第一种,最常用的,通过for in遍历数组 colours = ["red","green","blue"] ...

  2. python3(4)--- python遍历数组的两种方法

    python遍历数组的两种方法 第一种,最常用的,通过for in遍历数组.其实本质就是取出来的是这个数组或者列表中的元素,和角标无关. colours = ["red",&quo ...

  3. python遍历数组的两种方法的代码

    工作过程中,把开发过程中较好的一些内容段备份一下,下面内容是关于python遍历数组的两种方法的内容,希望对小伙伴有用途. colours = ["red","green ...

  4. python 遍历数组的3种方法及常用的代码

    1.直接使用数组的元素进行遍历,但这种遍历方法效率较低,不推荐使用.可以使用 python中的 num或者 int数组. 2.使用 python中的my_num,该方法通过数组的末尾进行遍历,效率最高 ...

  5. python遍历字典的5种方法

    python遍历字典5种方法 方法一: 使用字典的键进行遍历. dict={"张三":90,'王五':87,'李四':99} for key in dict:print(" ...

  6. python遍历数组的两种方法加条件输出数组的值

    第一种方法 1.通过for in遍历数组. 其实本质就是取出来的是这个数组或者列表中的元素,和角标无关. for predict_scores in predict_scores:print(pred ...

  7. python 遍历目录_Python遍历目录的4种方法实例介绍

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

  8. python遍历目录_Python遍历目录的4种方法

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

  9. python遍历字典的四种方法

    根据key值遍历 >>> a {'a': '1', 'b': '2', 'c': '3'} >>> for key in a:print(key+':'+a[key ...

最新文章

  1. c语言多线程mysql_多线程读写mysql数据库
  2. C言语教程第五章:函数(1)
  3. [JAVA基础] 成员变量和局部变量(一看就懂的总结归纳篇)
  4. LINUX系统管理命令
  5. java的数列极差_[hoj]数列极差问题 | 学步园
  6. cordova 支付_Cordova打包教程(H5项目打包成ipa)
  7. mysql8.0安装问题
  8. 51nod 1274 最长递增路径(DP)
  9. 数据结构(线性表)——神奇的幻方
  10. 【机器人操作系统】ROS工作空间及功能包的创建
  11. 反向传播与梯度消失梯度爆炸
  12. 英文单词乱序后还原 c语言,乱序背单词_有谁也用《不背单词》这个软件吗怎么可以改变背单词的顺序有顺序倒序和乱序的_淘题吧...
  13. php匹配ubb,UBB类 php UBB 解析实现代码
  14. Router入门0x205: react-route + redux + react 集成
  15. HTML中加入背景音乐
  16. EasySwoole3 Crontab的使用
  17. 微信小程序刷新页面数据
  18. 查看java安装路径[linux]
  19. 【Node】Error: ENOENT: no such file or directory,解决方案
  20. 电子技术——反馈对放大器极点的影响

热门文章

  1. iOS 键盘遮挡输入框万能解决方案(多个输入框)
  2. HashMap 和 HashTable 区别
  3. python中字典的增删改查及其他常用操作
  4. HDU6156 Palindrome Function
  5. linux下添加用户并赋予root权限
  6. 关于EF查询表里的部分字段
  7. 【产品经理求职攻略】10年产品人经验分享
  8. 罗辑思维年终4小时演讲《时间的朋友》1000字浓缩版
  9. 谈家政O2O平台的出路
  10. RXThink 官方网站正式上线