python 擷取目前的目錄下的檔案目錄和檔案名稱

來源:互聯網
上載者:User

標籤: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 擷取目前的目錄下的檔案目錄和檔案名稱

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.