欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python 标准库之 glob 介绍(获取文件夹下所有同类文件)

发布时间:2025/3/15 python 42 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python 标准库之 glob 介绍(获取文件夹下所有同类文件) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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 globfor 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 themif name[:-3] == "__init__" or name[:-3] == "clientbase":passelse:__import__("beeswarm.drones.client.baits." + name[:-3])

 

自己的实例:

__init__.py

import os import glob import logginglogger = logging.getLogger(__name__)obj = []for fullname in glob.glob(os.path.dirname(__file__) + "/*.py"):name = os.path.basename(fullname)if name[:-3] == "__init__":passelse: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 标准库之 glob 介绍(获取文件夹下所有同类文件)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。