問題描述
您可以使用 ftplib 在 Python 中獲得完整的 FTP 支持.然而,獲取目錄列表的首選方式是:
You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:
# File: ftplib-example-1.py
import ftplib
ftp = ftplib.FTP("www.python.org")
ftp.login("anonymous", "ftplib-example-1")
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
print "-", line
產(chǎn)量:
$ python ftplib-example-1.py
- total 34
- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .
- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 ..
- drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS
- lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -> welcome.msg
- drwxr-xr-x 3 root wheel 512 May 19 1998 bin
- drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev
- drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup
- drwxr-xr-x 3 root wheel 512 May 19 1998 etc
...
我想這個(gè)想法是解析結(jié)果以獲取目錄列表.但是,此列表直接取決于 FTP 服務(wù)器格式化列表的方式.必須預(yù)測 FTP 服務(wù)器可能會格式化此列表的所有不同方式,為此編寫代碼會非常麻煩.
I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.
有沒有一種可移植的方式來獲取一個(gè)包含目錄列表的數(shù)組?
Is there a portable way to get an array filled with the directory listing?
(數(shù)組應(yīng)該只有文件夾名稱.)
(The array should only have the folder names.)
推薦答案
嘗試使用 ftp.nlst(dir)
.
但請注意,如果文件夾為空,則可能會引發(fā)錯(cuò)誤:
However, note that if the folder is empty, it might throw an error:
files = []
try:
files = ftp.nlst()
except ftplib.error_perm as resp:
if str(resp) == "550 No files found":
print "No files in this directory"
else:
raise
for f in files:
print f
這篇關(guān)于使用 Python 的 ftplib 獲取目錄列表,可移植的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!