os模塊下有兩個函數:
os.walk()
os.listdir()
# -*- coding: utf-8 -*- import os def file_name(file_dir): for root, dirs, files in os.walk(file_dir): print(root) #當前目錄路徑 print(dirs) #當前路徑下所有子目錄 print(files) #當前路徑下所有非目錄子文件
輸出格式為:
當前文件目錄路徑
當前路徑下子文件目錄(若存在, 不存在則為 [] )
當前路徑下非目錄子文件(僅為子文件的文件名)
子文件1路徑
子文件1下的子文件目錄
子文件1下的非目錄子文件
子文件2路徑
子文件2下的子文件目錄
子文件2下的非目錄子文件
# -*- coding: utf-8 -*- import os def file_name(file_dir): L=[] for root, dirs, files in os.walk(file_dir): for file in files: if os.path.splitext(file)[1] == '.jpeg': L.append(os.path.join(root, file)) return L #其中os.path.splitext()函數將路徑拆分為文件名+擴展名
# -*- coding: utf-8 -*- import os def listdir(path, list_name): #傳入存儲的list for file in os.listdir(path): file_path = os.path.join(path, file) if os.path.isdir(file_path): listdir(file_path, list_name) else: list_name.append(file_path)
遞歸輸出當前路徑下所有非目錄子文件