python 獲取當前目錄下的文件目錄和文件名


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)

遞歸輸出當前路徑下所有非目錄子文件

    

  

 


免責聲明!

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



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