一、獲取指定目錄下、指定後綴的文件名列表
"""
函數說明:獲取指定目錄下的、指定後綴的文件
例如:.xlsx、.json
Parameters:
path - 目錄所在的路徑 例如 path='D:\Python Example\Tianyancha\Data'
suffix - 後綴,例如'.xlsx'
Returns:
input_template_All - 指定後綴的所有文件名
Author:
heda3
Blog:
https://blog.csdn.net/heda3
Modify:
2019-10-12
"""
#參考:https://www.runoob.com/python/os-listdir.html
def getFileName1(path,suffix):
# 獲取指定目錄下的所有指定後綴的文件名
input_template_All=[]
f_list = os.listdir(path)#返回文件名
for i in f_list:
# os.path.splitext():分離文件名與擴展名
if os.path.splitext(i)[1] ==suffix:
input_template_All.append(i)
#print(i)
return input_template_All
二、(升級版)獲取指定目錄下指定後綴的文件名列表和文件名+目錄的拼接
例如:D:\Python Example\Tianyancha\Data\xx.xlsx
"""
函數說明:獲取指定目錄下的、指定後綴的文件名及路徑+文件名的拼接
例如:.xlsx、.json
Parameters:
path - 目錄所在的路徑 例如 path='D:\Python Example\Tianyancha\Data'
suffix - 後綴,例如'.xlsx'
Returns:
input_template_All - 指定後綴的所有文件名 xx.xlsx
input_template_All_Path - 文件名和該路徑的拼接 例如:D:\Python Example\Tianyancha\Data\xx.xlsx
Author:
heda3
Blog:
https://blog.csdn.net/heda3
Modify:
2019-10-12
"""
#參考:https://www.runoob.com/python/os-walk.html
def getFileName2(path,suffix):
input_template_All=[]
input_template_All_Path=[]
for root, dirs, files in os.walk(path, topdown=False):
for name in files:
#print(os.path.join(root, name))
print(name)
if os.path.splitext(name)[1] == suffix:
input_template_All.append(name)
input_template_All_Path.append(os.path.join(root, name))
return input_template_All,input_template_All_Path
測試案例:
import os
path='D:\Python Example\Tianyancha\Data'
input_template_All1=getFileName1(path,'.xlsx')
input_template_All2,input_template_All_Path2=getFileName2(path,'.xlsx')
可更該爲獲取當前目錄:
os.path.abspath('.')#獲取當前工作目錄路徑 介紹其它獲取方法https://www.cnblogs.com/Jomini/p/8636129.html
參考文檔:
【1】Python os.listdir() 方法 https://www.runoob.com/python/os-listdir.html
【2】Python os.walk() 方法 https://www.runoob.com/python/os-walk.html
【3】os.path.split(path) 把路徑分割成 dirname 和 basename,返回一個元組
os.path.join(path1[, path2[, ...]]) 把目錄和文件名合成一個路徑
Python os.path() 模塊(全) https://www.runoob.com/python/python-os-path.html
walk()方法語法格式如下:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
參數
top -- 是你所要遍歷的目錄的地址, 返回的是一個三元組(root,dirs,files)。
- root 所指的是當前正在遍歷的這個文件夾的本身的地址
- dirs 是一個 list ,內容是該文件夾中所有的目錄的名字(不包括子目錄)
- files 同樣是 list , 內容是該文件夾中所有的文件(不包括子目錄)
topdown --可選,爲 True,則優先遍歷 top 目錄,否則優先遍歷 top 的子目錄(默認爲開啓)。如果 topdown 參數爲 True,walk 會遍歷top文件夾,與top 文件夾中每一個子目錄。
onerror -- 可選,需要一個 callable 對象,當 walk 需要異常時,會調用。
followlinks -- 可選,如果爲 True,則會遍歷目錄下的快捷方式(linux 下是軟連接 symbolic link )實際所指的目錄(默認關閉),如果爲 False,則優先遍歷 top 的子目錄。
返回值
該方法沒有返回值。