首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Python标准库glob用法精要

Python标准库glob用法精要

作者头像
Python小屋屋主
发布2018-04-16 14:58:27
发布2018-04-16 14:58:27
1.3K0
举报
文章被收录于专栏:Python小屋Python小屋

Python标准库glob提供了glob()和iglob()两个函数用来枚举指定文件夹中符合特定模式的文件列表,支持“?”和“*”通配符。

>>> import glob

# 查找所有扩展名为txt的文件

>>> glob.glob('c:\\Windows/*.txt')

['c:\\Windows\\acct.txt', 'c:\\Windows\\area.txt', 'c:\\Windows\\authsel.txt', 'c:\\Windows\\eap.txt', 'c:\\Windows\\eapkeep.txt', 'c:\\Windows\\guest.txt', 'c:\\Windows\\info.txt', 'c:\\Windows\\language.txt', 'c:\\Windows\\msginfosize.txt']

# 查找所有以字母a开头的txt文件

>>> glob.glob('c:\\Windows/a*.txt')

['c:\\Windows\\acct.txt', 'c:\\Windows\\area.txt', 'c:\\Windows\\authsel.txt']

# iglob()函数返回迭代器

>>> glob.iglob('c:\\Windows/*.txt')

<generator object iglob at 0x000000000357C5A0>

>>> for i in glob.iglob('c:\\Windows/*.txt'):

print(i)

c:\Windows\acct.txt

c:\Windows\area.txt

c:\Windows\authsel.txt

c:\Windows\eap.txt

c:\Windows\eapkeep.txt

c:\Windows\guest.txt

c:\Windows\info.txt

c:\Windows\language.txt

c:\Windows\msginfosize.txt

# 查找所有主文件名中第二个字母是a的txt文件

>>> glob.glob('c:\\Windows/?a*.txt')

['c:\\Windows\\eap.txt', 'c:\\Windows\\eapkeep.txt', 'c:\\Windows\\language.txt']

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2017-05-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python小屋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档