1 綜述
glob子產品是python最簡單的子產品之一, 用于查找符合特定規則的檔案路徑名,以
list
的形式傳回。
簡單用法示例:
首先在終端可以檢視目前檔案夾中的内容:
$ ls
csv_test decorators exception_handling plot_loss python_exercise python_thread
在python中可以看到
glob.glob()
傳回的内容:
>>> import glob
>>> glob.glob("./*")
['./decorators', './python_exercise', './exception_handling', './plot_loss', './python_thread', './csv_test']
2 比對符
查找檔案最用到的比對符有三個:"*", “?”, “[]” ,其實用法和正規表達式一樣。
2.1 "*"比對任意0個或多個字元
用法示例:
在終端可以檢視到目前檔案夾的内容:
$ ls
all_objects.py first_decorator.py partial_test.py test2.py test.py wraps_decorator.py
def_fun_in_fun.py fun_arg.py return_fun.py test3.py testx.py
假設使用python在此檔案夾查找以“test”開頭且以".py"結尾的檔案路徑:
>>> import glob
>>> glob.glob("./test*.py")
['./test3.py', './test.py', './testx.py', './test2.py']
2.2 "?"比對任意單個字元
用法示例:
在終端可以檢視到目前檔案夾的内容:
$ ls
all_objects.py first_decorator.py partial_test.py test2.py test.py
def_fun_in_fun.py fun_arg.py return_fun.py test3.py wraps_decorator.py
假設使用python在此檔案夾查找以“test”+”n"為檔案名且以".py"為字尾的檔案路徑:
>>> import glob
>>> glob.glob("./test?.py")
['./test3.py', './testx.py', './test2.py']
2.3 "[]"比對指定範圍内的字元
用法示例:
在終端可以檢視到目前檔案夾的内容:
$ ls
all_objects.py first_decorator.py partial_test.py test2.py test.py
def_fun_in_fun.py fun_arg.py return_fun.py test3.py wraps_decorator.py
假設使用python在此檔案夾查找以“test”+”n"為檔案名(“n"為一位阿拉伯數字)且以”.py"為字尾的檔案路徑:
>>> import glob
>>> glob.glob("./test[0-9].py")
['./test3.py', './test2.py']