要求
1、遍歷文件夾ddd下面所有的文件
2、並且獲取所有文件所在文件夾的名稱
解決方案
思路:先獲取某個路徑下面的其他路徑,然后循環遍歷,判斷這個路徑到底是文件路徑還是文件夾路徑,如果是文件路徑,直接添加到集合里面,如果是文件夾的話,就遞歸循環遍歷;
import os ##第一步、加載文件,獲取文件路徑以及標簽 train_path="./data/ddd" allpath=[] lllables=[] def get_lableandwav(path,dir): dirs = os.listdir(path) for a in dirs: print(a) print(os.path.isfile(path+"/"+a)) if os.path.isfile(path+"/"+a): allpath.append(dirs) if dir!="": lllables.append(dir) else: get_lableandwav(str(path)+"/"+str(a),a) ##循環遍歷這個文件夾 return allpath,lllables ##第一步、加載文件,獲取文件路徑以及標簽 [allpath,lllables]=get_lableandwav(train_path,"") print(allpath) print("----------") print(lllables)