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.

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