Python獲取路徑下所有檔名
摘要:
os 模組下有兩個函式:
os.walk()
os.listdir()
1# -*- coding: utf-8 -*-
2
3import os
4
5def file_name(file_dir):
...
os 模組下有兩個函式:
os.walk()
os.listdir()
1# -*- coding: utf-8 -*- 2 3import os 4 5def file_name(file_dir): 6for root, dirs, files in os.walk(file_dir): 7print(root) #當前目錄路徑 8print(dirs) #當前路徑下所有子目錄 9print(files) #當前路徑下所有非目錄子檔案
# 只獲取當前路徑下檔名,不獲取資料夾中檔名 1# -*- coding: utf-8 -*- 2 3import os 4 5def file_name(file_dir): 6L=[] 7for root, dirs, files in os.walk(file_dir): 8for file in files: 9if os.path.splitext(file)[1] == '.jpeg':# 想要儲存的檔案格式 10L.append(os.path.join(root, file)) 11return L 12 13 14 #其中os.path.splitext()函式將路徑拆分為檔名+副檔名
# 遞迴獲取路徑下所有檔名 1# -*- coding: utf-8 -*- 2import os 3 4def listdir(path, list_name):#傳入儲存的list 5for file in os.listdir(path): 6file_path = os.path.join(path, file) 7if os.path.isdir(file_path): 8listdir(file_path, list_name) 9else: 10list_name.append(file_path)