如何深入探讨Python标准库中的glob模块应用?

2026-05-28 21:341阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计434个文字,预计阅读时间需要2分钟。

如何深入探讨Python标准库中的glob模块应用?

pythonimport glob

for name in glob.glob('dir/**'): print(name)

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、单个字符通配符

用问号(?)匹配任何单个的字符。

如何深入探讨Python标准库中的glob模块应用?

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

知识点补充:Python编程:glob模块进行文件名模式匹配

文件准备

$ mkdir tmp
$ cd tmp
$ touch file1.txt
$ touch file2.txt
$ touch file3.log
$ ls
file1.txt file2.txt file3.log

测试

import glob # 使用零个或多个字符通配符 * glob.glob("tmp/*.txt") Out[1]: ['file1.txt', 'file2.txt'] # 使用单字符通配符 ? glob.glob("tmp/file?.txt") Out[2]: ['file1.txt', 'file2.txt'] # 使用范围匹配 glob.glob("tmp/file[0-9].txt") Out[3]: ['file1.txt', 'file2.txt']

总结

到此这篇关于浅析python标准库中的glob的文章就介绍到这了,更多相关python标准库 glob内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

标签:glob文件

本文共计434个文字,预计阅读时间需要2分钟。

如何深入探讨Python标准库中的glob模块应用?

pythonimport glob

for name in glob.glob('dir/**'): print(name)

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、单个字符通配符

用问号(?)匹配任何单个的字符。

如何深入探讨Python标准库中的glob模块应用?

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

知识点补充:Python编程:glob模块进行文件名模式匹配

文件准备

$ mkdir tmp
$ cd tmp
$ touch file1.txt
$ touch file2.txt
$ touch file3.log
$ ls
file1.txt file2.txt file3.log

测试

import glob # 使用零个或多个字符通配符 * glob.glob("tmp/*.txt") Out[1]: ['file1.txt', 'file2.txt'] # 使用单字符通配符 ? glob.glob("tmp/file?.txt") Out[2]: ['file1.txt', 'file2.txt'] # 使用范围匹配 glob.glob("tmp/file[0-9].txt") Out[3]: ['file1.txt', 'file2.txt']

总结

到此这篇关于浅析python标准库中的glob的文章就介绍到这了,更多相关python标准库 glob内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

标签:glob文件