本文採用os.walk()
和os.listdir()
兩種方法,獲取指定資料夾下的檔名。
模組os中的walk()函式可以遍歷資料夾下所有的檔案。
os.walk(top, topdown=ture, onerror=none, followlinks=false)
該函式可以得到乙個三元tupple(dirpath, dirnames, filenames).
引數含義:
- dirpath:string,代表目錄的路徑;
- dirnames:list,包含了當前dirpath路徑下所有的子目錄名字(不包含目錄路徑);
- filenames:list,包含了當前dirpath路徑下所有的非目錄子檔案的名字(不包含目錄路徑)。
注意,dirnames和filenames均不包含路徑資訊,如需完整路徑,可使用os.path.join(dirpath, dirnames)
下面給出**:
# -*- coding: utf-8 -*-
import os
deffile_name
(file_dir):
for root, dirs, files in os.walk(file_dir):
print(root) #當前目錄路徑
print(dirs) #當前路徑下所有子目錄
print(files) #當前路徑下所有非目錄子檔案
當需要特定型別的檔案時,**如下:
# -*- coding: utf-8 -*-
import os
deffile_name
(file_dir):
l=
for root, dirs, files in os.walk(file_dir):
for file in files:
if os.path.splitext(file)[1] == '.jpeg':
return l
其中os.path.splitext()函式將路徑拆分為檔名+副檔名,例如os.path.splitext(「e:/lena.jpg」)將得到」e:/lena「+」.jpg」。
os.listdir()函式得到的是僅當前路徑下的檔案
名,不包括子目錄中的檔案,所有需要使用遞迴的方法得到全部檔名。
直接給出**,函式將返回型別為『.jpeg』個檔名:
# -*- coding: utf-8 -*-參考這裡import os
deflistdir
(path, list_name):
for file in os.listdir(path):
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
listdir(file_path, list_name)
elif os.path.splitext(file_path)[1]=='.jpeg':
Python獲取指定資料夾下的檔名
本文採用os.walk 和os.listdir 兩種方法,獲取指定資料夾下的檔名。模組os中的walk 函式可以遍歷資料夾下所有的檔案。os.walk top,topdown ture,nerr r none,followlinks false 該函式可以得到乙個三元tupple dirpath,d...
Python獲取指定資料夾下的檔名
os.walk 和os.listdir 兩種方法 一 os.walk 模組os中的walk 函式可以遍歷資料夾下所有的檔案。os.walk top,topdown ture,onerror none,followlinks false 該函式可以得到乙個三元tupple dirpath,dirnam...
Python 獲取指定資料夾下的目錄和檔案的實現
經常有需要掃瞄目錄,對檔案做批量處理的需求,所以對目錄處理這塊做了下學習和總結。python 中掃瞄目錄有兩種方法 os.listdir 和 os.walk。一 os.listdir 方法 os.listdir 方法用於返回指定的目錄下包含的檔案或子目錄的名字的列表。這個列表以字母程式設計客棧順序。...