http://www.cnblogs.com/lovemo1314/archive/2011/04/26/2029556.html
說明:
glob是python自己帶的一個文件操作相關模塊,用它可以查找符合自己目的的文件,類似於Windows下的文件搜索,支持通配符操作,,?,[]這三個通配符,代表0個或多個字符,?代表一個字符,[]匹配指定范圍內的字符,如[0-9]匹配數字。兩個主要方法如下。
1. glob方法:
glob模塊的主要方法就是glob,該方法返回所有匹配的文件路徑列表(list);該方法需要一個參數用來指定匹配的路徑字符串(字符串可以為絕對路徑也可以為相對路徑),其返回的文件名只包括當前目錄里的文件名,不包括子文件夾里的文件。
比如:
glob.glob(r’c:*.txt’)
我這里就是獲得C盤下的所有txt文件
glob.glob(r’E:\pic**.jpg’)
獲得指定目錄下的所有jpg文件
使用相對路徑:
glob.glob(r’../*.py’)
2. iglob方法:
獲取一個迭代器( iterator )對象,使用它可以逐個獲取匹配的文件路徑名。與glob.glob()的區別是:glob.glob同時獲取所有的匹配路徑,而 glob.iglob一次只獲取一個匹配路徑。下面是一個簡單的例子:
#父目錄中所有的.py文件
f = glob.iglob(r'../*.py') print f <generator object iglob at 0x00B9FF80> for py in f: print py
- 1
- 2
- 3
- 4
- 5
- 6
f是一個迭代器對象,通過遍歷,可以輸出所有滿足條件的*.py文件
官方說明:
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). glob.iglob(pathname) Return an iterator which yields the same values as glob() without actually storing them all simultaneously. New in version 2.5.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
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.
>>> import glob >>> glob.glob('./[0-9].*') ['./1.gif', './2.txt'] >>> glob.glob('*.gif') ['1.gif', 'card.gif'] >>> glob.glob('?.gif') ['1.gif']