Python Glob模块

本文介绍了Python中的glob模块,该模块提供了基于Unix shell风格的通配符查找文件的功能。主要讲解了glob.glob和glob.iglob两个函数的使用方法及注意事项。
1. glob.glob(pathname) 返回所有匹配的文件路径列表

    Return a 可空的 list of path names that match pathname, which must be a string containing a path specification. 

    pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell).

import glob
 
#获取指定目录下的所有图片
print glob.glob(r"E:/Picture/*/*.jpg")
 
#获取上级目录的所有.py文件
print glob.glob(r'../*.py') #相对路径
        在查找的条件中,需要用到Unix shell中的匹配规则:
           *    :   匹配所所有
           ?    :   匹配一个字符
           *.*  :   匹配如:[hello.txt,cat.xls,xxx234s.doc]
           ?.*  :   匹配如:[1.txt,h.py]
           ?.gif:   匹配如:[x.gif,2.gif]

    查找文件只用到三个匹配符:”*”, “?”, “[]”。”*”匹配0个或多个字符;”?”匹配单个字符;”[]”匹配指定范围内的字符,如:[0-9]匹配数字。

2. glob.iglob(pathname)

    Return an iterator which yields the same values as glob() without actually storing them all simultaneously.glob.iglob 

        一次只获取一个匹配路径。这有点类似于.NET中操作数据库用到的DataSet与DataReader。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值