Python:glob模块

glob是python自己带的一个文件操作相关模块,用它可以查找符合自己目的的文件,就类似于Windows下的文件搜索,支持通配符操作(*  ?  []),*代表0个或多个字符,?代表一个字符,[]匹配指定范围内的字符,如[0-9]匹配数字。

1. glob模块通配符

通配符 功能
* 匹配0或多个字符
** 匹配所有文件,目录,子目录和子目录里面的文件 (3.5版本新增)
匹配一个字符,这里与正则表达式? (正则?匹配前面表达式0次或者1次)
[] 匹配指定范围内的字符,如: [1-9]匹配1至9内的字符
[!] 匹配不在指定范围内的字符

单字通配符?,当前路径文件下以file开头后有一个字符的py文件

for fname in glob.glob("./file?.py"):
    print(fname)

范围通配符[],当前路径文件下以file开头后一个数字符的py文件

for fname in glob.glob("./file[0-9].py"):
    print(fname)

范围通配符[],当前路径文件下以file开头后一个非数字符的py文件

for fname in glob.glob("./file[!0-9].py"):
    print(fname)

2. glob()方法

glob模块的主要方法是glob(),该方法返回所有匹配的文件路径列表,该方法需要一个参数用来指定匹配的路径字符串(本字符串可以为绝对路径也可以为相对路径);返回值:返回的文件名只包括当前目录里的文件名,不包括子文件夹里的文件。

比如:

import glob

# 绝对路径:
glob.glob(r'c:\*.txt')            # 获得C盘下的所有txt文件
glob.glob(r'E:\pic\*\*.jpg')      # 获得指定目录下的所有jpg文件

# 相对路径:
glob.glob(r'../*.py')

# 通配符
glob.glob('./[0-9].*')
# ['./1.gif', './2.txt']

glob.glob('*.gif')
# ['1.gif', 'card.gif']

glob.glob('?.gif')
# ['1.gif']

官方说明:

glob.glob(pathname)

Return a possibly-empty 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 http://www.cnblogs.com/Tools/*/*.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell).

3. iglob()方法

使用iglob(),返回迭代器iterator效率更高。获取一个可编历对象,使用它可以逐个获取匹配的文件路径名。

与glob.glob()的区别是:glob.glob()同时获取所有的匹配路径,而 glob.iglob()一次只获取一个匹配路径。这有点类似于.NET中操作数据库用到的DataSet与DataReader。下面是一个简单的例子:

# 父目录中的.py文件
f = glob.iglob(r'../*.py')

print(f)      # <generator object iglob at 0x00B9FF80>

for py in f:
    print(py)

官方说明:

glob.iglob(pathname)

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

New in version 2.5.

For example, consider a directory containing only the following files: 1.gif, 2.txt, andcard.gif. glob() will produce the following results. Notice how any leading components of the path are preserved.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章