標籤:utf-8 lse for end pen style 擷取 print 檔案名稱
os模組下有兩個函數:
os.walk()
os.listdir()
1 # -*- coding: utf-8 -*- 2 3 import os 4 5 def file_name(file_dir): 6 for root, dirs, files in os.walk(file_dir): 7 print(root) #目前的目錄路徑 8 print(dirs) #當前路徑下所有子目錄 9 print(files) #當前路徑下所有非目錄子檔案
輸出格式為:
當前檔案目錄路徑
當前路徑下子檔案目錄(若存在, 不存在則為 [] )
當前路徑下非目錄子檔案(僅為子檔案的檔案名稱)
子檔案1路徑
子檔案1下的子檔案目錄
子檔案1下的非目錄子檔案
子檔案2路徑
子檔案2下的子檔案目錄
子檔案2下的非目錄子檔案
1 # -*- coding: utf-8 -*- 2 3 import os 4 5 def file_name(file_dir): 6 L=[] 7 for root, dirs, files in os.walk(file_dir): 8 for file in files: 9 if os.path.splitext(file)[1] == ‘.jpeg‘: 10 L.append(os.path.join(root, file)) 11 return L 12 13 14 #其中os.path.splitext()函數將路徑拆分為檔案名稱+副檔名
1 # -*- coding: utf-8 -*- 2 import os 3 4 def listdir(path, list_name): #傳入儲存的list 5 for file in os.listdir(path): 6 file_path = os.path.join(path, file) 7 if os.path.isdir(file_path): 8 listdir(file_path, list_name) 9 else: 10 list_name.append(file_path)
遞迴輸出當前路徑下所有非目錄子檔案
python 擷取目前的目錄下的檔案目錄和檔案名稱