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

2022-01-09 00:00:00 python ftp portability

问题描述

您可以使用 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

产量:

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

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

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


解决方案

尝试使用 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 as resp:
    if str(resp) == "550 No files found":
        print "No files in this directory"
    else:
        raise

for f in files:
    print f

相关文章