十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
這篇文章主要介紹python如何列出文件夾所有文件,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
導入庫
首先,我們需要os庫中的三種方法。
l listdir:檢索目錄的內(nèi)容(目錄和文件)。
l join:將兩個組件組合成一條路徑。
l isfile:如果給定的路徑組件是一個文件,則返回true。
from os import listdir from os.path import join, isfile
檢索目錄的內(nèi)容
導入必要的方法后,該設置目錄的路徑并檢索其內(nèi)容了。
from os import listdir from os.path import join, isfile directory_path = "/some/path" contents = listdir(directory_path)
篩選目錄
現(xiàn)在我們有了目錄的所有內(nèi)容,是時候過濾掉目錄了—僅保留文件。
from os import listdir from os.path import join, isfile directory_path = "/some/path" contents = listdir(directory_path) files = filter(lambda f: isfile(join(directory_path,f)),contents)
files為列表以打印內(nèi)容
from os import listdir from os.path import join, isfile directory_path = "/Users/jhsu/Desktop" contents = listdir(directory_path) files = filter(lambda f: isfile(join(directory_path,f)),contents) print(files) #print(list(files)) # [list of files]
以上是python如何列出文件夾所有文件的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!