python 标准库之 glob 介绍(获取文件夹下所有同类文件)
2023-09-11 14:14:47 时间
python标准库之glob介绍
glob 文件名模式匹配,不用遍历整个目录判断每个文件是不是符合。
1、通配符
星号(*)匹配零个或多个字符
import glob
for name in glob.glob('dir/*'):
print (name)
dir/file.txt
dir/file1.txt
dir/file2.txt
dir/filea.txt
dir/fileb.txt
dir/subdir
列出子目录中的文件,必须在模式中包括子目录名:
import glob
#用子目录查询文件
print ('Named explicitly:')
for name in glob.glob('dir/subdir/*'):
print ('\t', name)
#用通配符* 代替子目录名
print ('Named with wildcard:')
for name in glob.glob('dir/*/*'):
print ('\t', name)
Named explicitly:
dir/subdir/subfile.txt
Named with wildcard:
dir/subdir/subfile.txt
2、单个字符通配符
用问号(?)匹配任何单个的字符。
import glob
for name in glob.glob('dir/file?.txt'):
print (name)
dir/file1.txt
dir/file2.txt
dir/filea.txt
dir/fileb.txt
3、字符范围
当需要匹配一个特定的字符,可以使用一个范围
import glob
for name in glob.glob('dir/*[0-9].*'):
print (name)
dir/file1.txt
dir/file2.txt
源码实例:__init__.py
import os
import glob
# Detect all modules
for fullname in glob.glob(os.path.dirname(__file__) + "/*.py"):
name = os.path.basename(fullname)
# __init__ and clientbase are not capabilities, so ignore them
if name[:-3] == "__init__" or name[:-3] == "clientbase":
pass
else:
__import__("beeswarm.drones.client.baits." + name[:-3])
自己的实例:
__init__.py
import os
import glob
import logging
logger = logging.getLogger(__name__)
obj = []
for fullname in glob.glob(os.path.dirname(__file__) + "/*.py"):
name = os.path.basename(fullname)
if name[:-3] == "__init__":
pass
else:
obj.append(name[:-3])
main.py
for cl in protocol.obj:
if self.server == cl:
metaclass = importlib.import_module("protocol." + cl)
gsl = metaclass.pot()
gsl.start()
相关文章
- 优志愿前端数据加密破解-python
- Python基于正则表达式实现文件内容替换的方法
- 小白学 Python(18):基础文件操作
- Python判断文件和文件夹是否存在的方法
- 【Python】python对象与json相互转换
- python pyyaml模块使用示例:读取yaml文件内容
- Python 这样 print 才够骚啊
- Python:利用python语言实现18位身份证号码和15位身份证号码相互转换
- Python语言学习之双下划线那些事:python和双下划线使用方法之详细攻略
- 已解决2.Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and wi
- 〖Python 数据库开发实战 - Python与Redis交互篇⑮〗- 综合案例 - 新闻管理系统 - 更新所编辑新闻状态(根据输入内容进行保存操作)
- 【Python成长之路】装逼的一行代码:快速共享文件【华为云分享】
- 【华为机试真题 Python实现】最远足迹【2022 Q1 Q2 | 100分】
- python XML文件解析:用ElementTree解析XML
- python getmtime() 最近修改文件内容的时间
- 经验分享:如何零基础开始自学Python编程(下)
- 【Python】对字典进行排序
- 【异常】前端ERR! stack Error: Can‘t find Python executable “python“, you can set the PYTHON env variable.