基于py36的glob模块总结
glob介紹
glob是python自帶的一個操作文件的相關模塊。用它可以查找符合特定規則的文件路徑名。使用該模塊查找文件,只需要用到: “*”, “?”, “[]”, “**”這四個匹配符;
* : 匹配所有字符 ? : 匹配一個字符 [] : 匹配指定范圍內的字符,如[0-9]匹配數字。 ** : 匹配所有文件、目錄、子目錄和子目錄里的文件(需配合其他參數)下面實例的目錄結構
glob.glob
函數分析
glob.glob(pathname, *, recursive=False)
pathname : 要匹配的文件名稱* :非參數,只是限定符recursive : If recursive is true, the pattern '**' will match any files and zero or more directories and subdirectories. 默認為False如果有匹配,glob.glob(path)的結果放入一個列表中返回如果沒有匹配的,glob.glob(path)將返回一個空的list:[]實例驗證
res = glob.glob(’.\imgs\**’, recursive=False)
print(res)
[’.\imgs\cat.png’, ‘.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’, ‘.\imgs\one_dir’]
res = glob.glob(’.\imgs\**’, recursive=True)
print(res)
[’.\imgs\’, ‘.\imgs\cat.png’, ‘.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’, ‘.\imgs\one_dir’, ‘.\imgs\one_dir\one_file.py’, ‘.\imgs\one_dir\one_file.txt’]
當**匹配符遇到recursive=True,擦出了不一樣的火花
-
匹配imgs路徑下的所有文件/路徑
res = glob.glob(’.\imgs\*’, recursive=True)
print(res)
[’.\imgs\cat.png’, ‘.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’, ‘.\imgs\one_dir’]
res = glob.glob(’.\imgs\*’, recursive=False)
print(res)
[’.\imgs\cat.png’, ‘.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’, ‘.\imgs\one_dir’]
recursive無論為True還是False 對于*匹配符都是沒有影響的。 -
只匹配目錄下的所有文件,不再匹配目錄下的目錄
res = glob.glob(’.\imgs\*.*’)
print(res)
[’.\imgs\cat.png’, ‘.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’]
-
過濾出所有txt文件
res = glob.glob(’.\imgs\*.txt’, recursive=False)
print(res)
[’.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’] -
匹配當前路徑下面的路徑下的所有png圖片
res = glob.glob(’.\*\*.png’)
print(res)
[’.\imgs\cat.png’]
-
只匹配hello0.txt到hello9.txt
res = glob.glob(’.\imgs\hello?.txt’)
print(res)
[’.\imgs\hello0.txt’, ‘.\imgs\hello2.txt’] -
獲取目錄下文件名為6個字符的文件
res = glob.glob(’.\imgs\??????.*’)
print(res)
[’.\imgs\hello0.txt’, ‘.\imgs\hello2.txt’]
-
只匹配hello0.txt到hello9.txt
res = glob.glob(’.\imgs\hello[0-9].txt’)
print(res)
[’.\imgs\hello0.txt’, ‘.\imgs\hello2.txt’] -
匹配imgs目錄下包含數字的文件
res = glob.glob(’.\imgs\*[0-9]*.*’)
print(res)
[’.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’]
glob函數默認不搜索以.點號開頭的文件和路徑,如果要求的話需要單獨寫個點號.
res = glob.glob(’.\imgs\.*.*’)
print(res)
[’.\imgs\.pip.config’]
glob.iglob函數分析
iglob(pathname, *, recursive=False)
iglob和glob.glob的用法一樣。區別就在于它返回的是一個生成器。
res = glob.iglob(’.\imgs\*[0-9]*.*’)
print(res)
<generator object _iglob at 0x000001F508DA4678>
for r in res:
print(r)
.\imgs\hello0.txt
.\imgs\hello100.txt
.\imgs\hello2.txt
glob.escape函數分析
escape(pathname)
輸入路徑名稱,轉義所有特殊字符
它返回的是一個glob規則,將 *,?,[] 這三個特殊符號轉換成可以去匹配含有這三個特殊符號字符串的glob規則
res = glob.escape(’.\imgs\*.txt’)
print(res)
.\imgs[*].txt
總結
以上是生活随笔為你收集整理的基于py36的glob模块总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多进程多线程处理文本数据
- 下一篇: windows10上为jupyter n