Python遍历目录的多种方式

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)
时间: 2024-08-03 09:03:31

Python遍历目录的多种方式的相关文章

用Python遍历目录

用Python遍历指定目录下的文件,一般有两种常用方法,但它们都是基于Python的os模块.下面两种方法基于Python2.7,主要用到的函数如下: 1.os.listdir(path):列出目录下的所有文件名 2.os.getcwd():获得当前工作目录 3.os.mkdir(dir):创建单个目录 4.os.makedirs('c:\python\a'):创建多级目录 5.os.rmdir(dir):删除单个目录 6.os.removedirs('D:\python'):删除所给路径最后一

Python模块导入的多种方式

在python中, 模块即一个后缀名为".py"文件,python用文件组织一个模块. 模块导入遵循作用域原则, 在什么作用域导入就只能在当前作用域生效. 一个模块只被加载一次,无论导入它多少次. from module import name 是把名字导入到当前的名称空间 单行导入单个模块 import json 单行导入多个模块 import os, sys, time 导入指定的模块属性 from os import path, fork, mkdir 多行导入 from Tki

Python遍历目录的4种方法

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

(转)Python 遍历List三种方式

转自: http://www.cnblogs.com/pizitai/archive/2017/02/14/6398276.html # 方法1 print '遍历列表方法1:' for i in list: print("序号:%s 值:%s" % (list.index(i) + 1, i)) print '\n遍历列表方法2:' # 方法2 for i in range(len(list)): print("序号:%s 值:%s" % (i + 1, list

python遍历目录

os.walk() 用元组表示(dirpath, dirnames, filenames): 第一个是根路径,dirpath为str类型: 第二个是根路径中的文件夹,dirnames为list类型: 第三个是根路径下的文件,filenames为list类型. 全路径表示法:os.path.join(dirpath, name).

Python递归遍历目录下所有文件

#自定义函数: import ospath="D:\\Temp_del\\a" def gci (path): parents = os.listdir(path) for parent in parents: child = os.path.join(path,parent) #print(child) if os.path.isdir(child): gci(child) # print(child) else: print(child) gci(path) #使用os.walk方

python学习记录第五篇--遍历目录

#coding=utf-8'''@author: 简单遍历目录删除文件的小程序'''import os#查找文件操作def findFile(path): fileList=[] for rootPath,subRoot,fileName in os.walk(path): for sub in fileName: if os.path.isfile(os.path.join(rootPath,sub)): k=os.path.splitext(sub)[1].lower() if k in (

[python小记]使用lxml修改xml文件,并遍历目录

这次的目的是遍历目录,把目标文件及相应的目录信息更新到xml文件中.在经过痛苦的摸索之后,从python自带的ElementTree投奔向了lxml.而弃用自带的ElementTree的原因就是,namespace. XML命名空间 作用是为避免元素命名冲突,当出现命名冲突的时候,可以使用前缀来避免命名冲突,就如: <h:table> <h:tr> <h:td>App Store</h:td> <h:td>Google Play</h:td

使用多种方式实现遍历HashMap

今天讲解的主要是使用多种方式来实现遍历HashMap取出Key和value,首先在java中如果想让一个集合能够用for增强来实现迭代,那么此接口或类必须实现Iterable接口,那么Iterable究竟是如何来实现迭代的,在这里将不做讲解,下面主要讲解一下遍历过程. //定义一个泛型集合 Map<String, String> map = new HashMap<String, String>(); //通过Map的put方法向集合中添加数据 map.put("001&