淺析python標準庫中的glob
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內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
1. 編程語言PHP在Web開發領域的優勢在哪?2. 詳解Android studio 動態fragment的用法3. Android如何加載Base64編碼格式圖片4. Spring Boot和Thymeleaf整合結合JPA實現分頁效果(實例代碼)5. 解決Android studio xml界面無法預覽問題6. 什么是python的自省7. 基于android studio的layout的xml文件的創建方式8. .Net Core使用Coravel實現任務調度的完整步驟9. Springboot Druid 自定義加密數據庫密碼的幾種方案10. 圖文詳解vue中proto文件的函數調用

網公網安備