簡介
glob模塊可以查找符合特定規則的文件路徑名。跟使用windows下的文件搜索差不多。它有三個匹配符:”*”, “?”, “[]”。
- *:匹配0個或多個字符;
- ?:匹配單個字符;
- []:匹配指定范圍內的字符,如:[a-z]匹配所有字母
方法介紹
- .glob(pathname, *, recursive=False)
"""Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. If recursive is true, the pattern '**' will match any files and zero or more directories and subdirectories. """ # recursive默認為False,表示只返回該路徑下的目錄及文件列表;如果為True,則路徑后應該跟**,可遞歸返回該路徑下的所有目錄及目錄下的文件,否則效果跟False一樣 glob.glob(r"C:\Users\Desktop\FinanicalBook\.*") # 返回所有的隱藏目錄及文件列表 glob.glob(r"C:\Users\Desktop\FinanicalBook\*") # 返回FinanicalBook目錄下的所有目錄及文件列表 glob.glob(r"C:\Users\Desktop\FinanicalBook\a*") # 返回以a開頭的目錄及文件列表 glob.glob(r"C:\Users\Desktop\FinanicalBook\*q") # 返回以q結尾的目錄及文件列表 glob.glob(r"C:\Users\Desktop\FinanicalBook\[a-c]*") # 返回以a-c開頭的目錄及文件列表 glob.glob(r"C:\Users\Desktop\FinanicalBook\**", recursive=True) # 遞歸匹配任何文件以及零個或多個目錄和子目錄
- .iglob(pathname, *, recursive=False)
用法跟glob()一樣,只不過該函數的返回值是一個generator(生成器)
- .escape(pathname)
""" Escape all special characters. Escaping is done by wrapping any of "*?[" between square brackets """ # 轉義所有特殊字符 # 轉義是通過在方括號之間包裝“*?[”來完成的 # 例: res = glob.escape(r"C:\Users\Desktop\FinanicalBook\*..\?\[A-Z^$|\res") # C:\Users\Desktop\FinanicalBook\[*]..\[?]\[[]A-Z^$|\res