python ftplib list,可移植地使用Python的ftplib获取目录列表

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

Which yields:

$ 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

...

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.

Is there a portable way to get an array filled with the directory listing?

(The array should only have the folder names.)

解决方案

However, note that if the folder is empty, it might throw an error:

files = []

try:

files = ftp.nlst()

except ftplib.error_perm, resp:

if str(resp) == "550 No files found":

print "No files in this directory"

else:

raise

for f in files:

print f

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值