glob是python自己帶的一個文件操作相關模塊,用它可以查找符合自己目的的文件,就類似於Windows下的文件搜索,支持通配符操作,*,?,[]這三個通配符,*代表0個或多個字符,?代表一個字符,[]匹配指定範圍內的字符,如[0-9]匹配數字。
它的主要方法就是glob,該方法返回所有匹配的文件路徑列表,該方法需要一個參數用來指定匹配的路徑字符串(本字符串可以爲絕對路徑也可以爲相對路徑),其返回的文件名只包括當前目錄裏的文件名,不包括子文件夾裏的文件。
python手機中的介紹:
The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched. This is done by using the os.listdir() and fnmatch.fnmatch() functions in concert, and not by actually invoking a subshell. (For tilde and shell variable expansion, useos.path.expanduser() and os.path.expandvars().)
- 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 ../../Tools/*/*.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell).
- glob.iglob(pathname) #返回迭代器
Return an iteratorwhich 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, and card.gif. glob() will produce the following results. Notice how any leading components of the path are preserved.
>>> importglob>>> glob.glob('./[0-9].*')['./1.gif', './2.txt']>>> glob.glob('*.gif')['1.gif', 'card.gif']>>> glob.glob('?.gif')['1.gif']
上代碼:
import glob
fileList = glob.glob(r'c:\*.txt')
print fileList
for file_name in fileList:
print file_name
print'*'*40
fileGen = glob.iglob(r'c:\*.txt')
print fileGen
for filename in fileGen:
print filename
結果:
['c:\\1.txt', 'c:\\adf.txt', 'c:\\baidu.txt', 'c:\\resultURL.txt']
c:\1.txt
c:\adf.txt
c:\baidu.txt
c:\resultURL.txt
****************************************
<generator object iglob at 0x01DC1E90>
c:\1.txt
c:\adf.txt
c:\baidu.txt
c:\resultURL.txt