可移植地使用Python的ftplib获取目录列表 [英] Using Python's ftplib to get a directory listing, portably

查看:327
本文介绍了可移植地使用Python的ftplib获取目录列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用ftplib在Python中提供完整的FTP支持。但是获取目录列表的首选方式是:

 #文件:ftplib-example-1.py 

导入ftplib

ftp = ftplib.FTP(www.python.org)
ftp.login(anonymous,ftplib-example-1)

data = []

ftp.dir(data.append)

ftp.quit()


print - ,line

其中:

  $ 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自述文件 - > welcome.msg
- drwxr-xr-x 3根轮盘512 5月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根盘轮512 1998年5月19日等
...

我想这个想法是解析结果以获取目录列表。但是,此列表直接取决于FTP服务器对列表进行格式化的方式。为此编写代码将非常麻烦,因为它不得不预测FTP服务器可能会对列表进行格式化的所有不同方式。

是否有一种可移植的方式让数组填充目录列表?



(该数组只能包含文件夹名称。)

解决方案

尝试使用 ftp .nlst(dir)



但是,请注意,如果该文件夹为空,则可能会引发错误:

  files = [] 

尝试:
files = ftp.nlst()
除ftplib.error_perm之外,其余为:
如果str(resp)==550没有找到文件:
print此目录中没有文件
else:
raise

用于文件中的f:
print f


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.)

解决方案

Try to use ftp.nlst(dir).

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

这篇关于可移植地使用Python的ftplib获取目录列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆