glob模块、递归查找、glob.glob()、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))   # <class 'generator'>

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
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Enzo 想砸电脑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值