Python列出資料夾下某類檔名的方法
阿新 • • 發佈:2018-11-11
Python 列出資料夾下某類檔案字尾
讀某個資料夾下所有圖片
利用
os.listdir()
和string.endswith()
函式實現。
在進行視覺相關任務程式設計時, 常常需要讀出資料夾下的圖片。但有的時候會包含其他字尾的檔案,這時候需要將特定字尾的檔名依次讀出。
python的字串提供了一個匹配結尾的函式string.endswith()
,其用法如下:
string.endswith(value, start, end)
引數 | 含義 |
---|---|
value | 字串 |
start | 檢測的起始位置 |
end | 檢測的終止位置 |
返回值 | True/False |
如果需要讀入的圖片為xxx.jpg
那麼就可以只用上述函式來判斷,下面是一個具體的使用例子:
#從資料夾中讀取所有的圖片
import os
import cv2
path = 'where/your/photo/stored'
names = os.listdir(path) #這將返回一個所有檔名的列表
for name in names:
if name. endswith('.jpg'): #如果以圖片jpg結尾則為真,同樣對於png,bmp,txt也適用
img = cv2.imread(path+name)
# Your process code
然後就可以愉快地讀入了~~~
icon from easyicon.net