最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python用glob模塊匹配路徑的方法詳解

 更新時間:2024年02月11日 12:05:01   作者:微小冷  
這篇文章主要介紹了python如何用glob模塊匹配路徑,glob模塊是Python的一個標準庫,用于在文件系統(tǒng)中查找文件名匹配特定模式的文件路徑,需要的朋友可以參考下

glob模塊是Python的一個標準庫,用于在文件系統(tǒng)中查找文件名匹配特定模式的文件路徑。

可以使用glob模塊進行文件系統(tǒng)的通配符匹配,類似于在命令行中使用*和?通配符進行文件查找。

glob

glob可以通過通配符查找路徑。例如

>>> import glob
>>> for i in range(10):
...   temp = open(str(i)+'.py','w')
...   temp.close()
...
>>> glob.glob(r'E:\Documents\00\1101\*.py')

返回值如下

[‘E:\Documents\00\1101\0.py’, ‘E:\Documents\00\1101\1.py’, ‘E:\Documents\00\1101\2.py’, ‘E:\Documents\00\1101\3.py’, ‘E:\Documents\00\1101\4.py’, ‘E:\Documents\00\1101\5.py’, ‘E:\Documents\00\1101\6.py’, ‘E:\Documents\00\1101\7.py’, ‘E:\Documents\00\1101\8.py’, ‘E:\Documents\00\1101\9.py’]

查看源碼可以發(fā)現(xiàn),glob是通過list(iglob(**))實現(xiàn)的,iglob返回一個符合要求路徑的迭代器,glob將其轉(zhuǎn)化為列表。

>>> it = glob.iglob(r'E:\Documents\00\1101\*.py')
>>> next(it)
'E:\\Documents\\00\\1101\\0.py'
>>> next(it)
'E:\\Documents\\00\\1101\\1.py'
>>> next(it)
'E:\\Documents\\00\\1101\\2.py'
>>> list(it)
['E:\\Documents\\00\\1101\\3.py', 'E:\\Documents\\00\\1101\\4.py', 'E:\\Documents\\00\\1101\\5.py', 'E:\\Documents\\00\\1101\\6.py', 'E:\\Documents\\00\\1101\\7.py', 'E:\\Documents\\00\\1101\\8.py', 'E:\\Documents\\00\\1101\\9.py']

fnmatch

除了*可以被轉(zhuǎn)義之外,glob還可以將[]?等字符進行轉(zhuǎn)義,其方法結(jié)合了os.scandir()fnmatch.fnmatch()函數(shù),例如

>>> glob.glob(r'E:\Documents\00\1101\[1-5].py')

[‘E:\Documents\00\1101\1.py’, ‘E:\Documents\00\1101\2.py’, ‘E:\Documents\00\1101\3.py’, ‘E:\Documents\00\1101\4.py’, ‘E:\Documents\00\1101\5.py’]

fnmatch是python中的文件夾匹配模塊,其匹配規(guī)則為

模式*?[seq][!seq]
含意所有字符任何單個字符seq中任何字符不在seq中的字符

fnmatch中封裝了一個正則表達式轉(zhuǎn)化函數(shù),可將fnmatch的匹配規(guī)則轉(zhuǎn)為正則表達式的匹配規(guī)則,例如

>>> fnmatch.translate('[1-5]*.py')
'(?s:[1-5].*\\.py)\\Z'

到此這篇關(guān)于python用glob模塊匹配路徑的方法詳解的文章就介紹到這了,更多相關(guān)python glob匹配路徑內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

玛多县| 石台县| 洛川县| 比如县| 迭部县| 蒙阴县| 巴林左旗| 富顺县| 荥经县| 房产| 宜兴市| 上杭县| 兴山县| 安化县| 广汉市| 旌德县| 阿克苏市| 明光市| 社旗县| 望城县| 博白县| 徐闻县| 迁西县| 依安县| 麻江县| 丹阳市| 翁牛特旗| 阳江市| 平顶山市| 萍乡市| 静宁县| 依安县| 涡阳县| 金堂县| 务川| 祁阳县| 密山市| 东源县| 柳江县| 从江县| 江安县|