glob模块、递归查找、glob.glob()、glob.iglob()

目录

  • 1、简介
  • 2、glob.glob() 函数的使用
  • 3、glob.iglob() 函数的使用


1、简介

  • glob 是 python 的标准库模块,只要安装 python 就可以使用该模块。
  • glob模块主要用来查找目录和文件,可以使用*、?、[] 这三种通配符对路径中的文件进行匹配。
    • *:代表 0个 或 多个 字符
    • ?:代表 一个字符
    • []:匹配指定范围内的字符,如 [0-9] 表示 0~9 中的数字

2、glob.glob() 函数的使用

glob.glob(pathname, *, recursive=False)
  • pathname:要匹配的路径
  • recursive:如果是true就会递归的去匹配符合的文件路径(配合 ** 使用),默认是False
test_dir/
├── a1.txt
├── a2.txt
├── a3.py
├── sub_dir1
│   ├── b1.txt
│   ├── b2.py
│   └── b3.py
└── sub_dir2
    ├── c1.txt
    ├── c2.py
    └── c3.txt

1、返回目录的路径列表

path_list1 = glob.glob('./test_dir/')
print(path_list1)
# ['./test_dir/']

2、匹配 './test_dir/*' 路径下的所有目录和文件,并返回路径列表

path_list2 = glob.glob('./test_dir/*')
print(path_list2)
# [
# './test_dir/a1.txt'
# './test_dir/a2.txt', 
# './test_dir/a3.py', 
# './test_dir/sub_dir1', 
# './test_dir/sub_dir2', 
# ]

3、匹配./test_dir/路径下含有的所有.py文件(不递归

path_list3 = glob.glob('./test_dir/*.py')
print(path_list3)
# ['./test_dir/a3.py']
path_list4 = glob.glob('./test_dir/*/*.py')
print(path_list4)
# [
# './test_dir/sub_dir1/b2.py', 
# './test_dir/sub_dir1/b3.py', 
# './test_dir/sub_dir2/c2.py'
# ]

4、递归的匹配./test_dir/**路径下的所有目录和文件,并返回路径列表

path_list5 = glob.glob('./test_dir/**', recursive=True)
print(path_list5)
# [
# './test_dir/', 
# './test_dir/a3.py', 
# './test_dir/a2.txt', 
# './test_dir/sub_dir1', 
# './test_dir/sub_dir1/b2.py', 
# './test_dir/sub_dir1/b3.py', 
# './test_dir/sub_dir1/b1.txt', 
# './test_dir/sub_dir2', 
# './test_dir/sub_dir2/c3.txt', 
# './test_dir/sub_dir2/c1.txt', 
# './test_dir/sub_dir2/c2.py', 
# './test_dir/a1.txt'
# ]
path_list6 = glob.glob('./test_dir/**/*.py', recursive=True)
print(path_list6)
# [
# './test_dir/a3.py', 
# './test_dir/sub_dir1/b2.py', 
# './test_dir/sub_dir1/b3.py', 
# './test_dir/sub_dir2/c2.py'
# ]

所以,如果要对某个路径下进行递归,一定要在后面加两个*


3、glob.iglob() 函数的使用

glob.iglob(pathname, recursive=False)
  • pathname:该参数是要匹配的路径
  • recursive:如果是true就会递归的去匹配符合的文件路径,默认是False

glob.iglob 的参数与 glob.glob() 参数一样,不一样的是,glob.iglob() 返回的是一个迭代器,如果遍历该迭代器,输出的结果与使用相同参数调用 glob.glob() 的返回结果是一致的

file_path_iter = glob.iglob('./test_dir/*')
print(type(file_path_iter))   # 

for file_path in file_path_iter:
    print(file_path)

# ./test_dir/a3.py
# ./test_dir/a2.txt
# ./test_dir/sub_dir1
# ./test_dir/sub_dir2
# ./test_dir/a1.txt

你可能感兴趣的:(#,python,python,深度学习,人工智能)