淺析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
知識點補充: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內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python使用Nocalhost并開啟debug調(diào)試的方法
Nocalhost是一種開發(fā)者工具,支持針對Kubernetes應用程序進行調(diào)試和部署,這篇文章主要介紹了Python怎么使用Nocalhost并開啟debug,需要的朋友可以參考下2023-04-04使用Python和XML實現(xiàn)文件復制工具的完整代碼
在本篇博客中,我們將學習如何使用 wxPython 構建一個簡單的文件復制工具,并將文件路徑和目標目錄的配置信息保存到 XML 文件中,通過這種方式,我們可以在下次運行程序時輕松加載之前保存的配置,需要的朋友可以參考下2024-08-08Python編程實現(xiàn)tail-n查看日志文件的方法
這篇文章主要介紹了Python編程實現(xiàn)tail-n查看日志文件的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07