python編程之循環遍歷文件夾下面的文件,以及獲取文件夾名稱


要求

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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM