您的位置:首頁技術文章
文章詳情頁

淺析python標準庫中的glob

瀏覽:3日期:2022-08-02 13:31:45

glob 文件名模式匹配,不用遍歷整個目錄判斷每個文件是不是符合。

1、通配符

星號(*)匹配零個或多個字符

import globfor name in glob.glob(’dir/*’): print (name)dir/file.txtdir/file1.txtdir/file2.txtdir/filea.txtdir/fileb.txtdir/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.txtNamed with wildcard: dir/subdir/subfile.txt

2、單個字符通配符

用問號(?)匹配任何單個的字符。

import globfor name in glob.glob(’dir/file?.txt’): print (name)dir/file1.txtdir/file2.txtdir/filea.txtdir/fileb.txt

3、字符范圍

當需要匹配一個特定的字符,可以使用一個范圍

import globfor name in glob.glob(’dir/*[0-9].*’): print (name)dir/file1.txtdir/file2.txt

知識點補充:Python編程:glob模塊進行文件名模式匹配

文件準備

$ mkdir tmp$ cd tmp$ touch file1.txt$ touch file2.txt$ touch file3.log$ lsfile1.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內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
国产综合久久一区二区三区