python模块:glob

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']

猜你喜欢

转载自blog.csdn.net/qyhaill/article/details/103357488