Python列出目錄
Python列出目錄
Python可用于從目錄獲取內(nèi)容列表??梢允褂贸绦蛄谐鲞\(yùn)行python的同一臺計(jì)算機(jī)中目錄的內(nèi)容。還可以登錄到遠(yuǎn)程系統(tǒng)并列出遠(yuǎn)程目錄中的內(nèi)容。
1. 列出本地目錄
在下面的示例中,使用listdir()方法獲取當(dāng)前目錄的內(nèi)容。要指示諸如文件或目錄之類的內(nèi)容類型,使用更多函數(shù)來評估內(nèi)容的性質(zhì)。
# Filename : example.py # Copyright : 2020 By Codebaoku # Author by : www.slktour.com # Date : 2020-08-25 for name in os.listdir('.'): if os.path.isfile(name): print 'file: ', name elif os.path.isdir(name): print 'dir: ', name elif os.path.islink(name): print 'link: ', name else: print 'unknown', name
當(dāng)運(yùn)行上面的程序時(shí),我們得到以下輸出 :
# Filename : example.py # Copyright : 2020 By Codebaoku # Author by : www.slktour.com # Date : 2020-08-25 file: index.html dir: mybooks link: ulink
請注意,以上內(nèi)容特定于運(yùn)行python程序的系統(tǒng)。結(jié)果將因系統(tǒng)及其內(nèi)容而異。
2. 列出遠(yuǎn)程目錄
可以使用ftp訪問遠(yuǎn)程系統(tǒng)來列出遠(yuǎn)程目錄的內(nèi)容。建立連接后,可以使用將以類似于本地目錄列表的方式列出目錄內(nèi)容的命令。
# Filename : example.py # Copyright : 2020 By Codebaoku # Author by : www.slktour.com # Date : 2020-08-25 from ftplib import FTP def main(): ftp = FTP('ftp.ibiblio.org') ftp.login() ftp.cwd('satic/yapf') # change to some other subject entries = ftp.nlst() ftp.quit() print(len(entries), "entries:") for entry in sorted(entries): print(entry) if __name__ == '__main__': main()
當(dāng)運(yùn)行上面的程序時(shí),得到以下輸出:
# Filename : example.py # Copyright : 2020 By Codebaoku # Author by : www.slktour.com # Date : 2020-08-25 (5, 'entries:') css uploads js python images
相關(guān)文章
- Python讀寫csv文件的操作方法
- Python中find函數(shù)如何使用
- Python修改列表元素的方法
- Python異步怎么使用等待有時(shí)間限制協(xié)程
- Python異步之怎么保護(hù)任務(wù)免于取消
- Python異步之迭代器怎么使用
- Python異步之上下文管理器怎么使用
- Python異步之生成器怎么使用
- Python數(shù)據(jù)可視化之Pyecharts如何使用
- Python 開發(fā)環(huán)境
- Python Internet 協(xié)議模塊
- Python HTTP標(biāo)頭
- Python 請求狀態(tài)代碼
- Python 電子郵件
- Python IMAP
- Python 上傳數(shù)據(jù)
- Python 遠(yuǎn)程過程調(diào)用
- Python 并發(fā)與并行
- Python 測試線程應(yīng)用程序
- Python 反應(yīng)式編程