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.
總結
以上是生活随笔為你收集整理的Python:glob模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python:docx模块
- 下一篇: Git 操作简单总结:廖雪峰教程