你可以使用ftplib全的FTP支持在蟒蛇。但是首选的方式获得的一个目录清单是:

# 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服务器的可能格式,这个名单。

有没有便携式方式得到一个填充阵列的目录列表?

(阵列应该只有该文件夹的名字。)

有帮助吗?

解决方案

尝试使用 ftp.nlst(dir)

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

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

其他提示

可靠/标准化方式分析FTP directory清单是通过使用MLSD命令,其中通过现在应该是支持通过所有最近的/不错FTP服务器。

import ftplib
f = ftplib.FTP()
f.connect("localhost")
f.login()
ls = []
f.retrlines('MLSD', ls.append)
for entry in ls:
    print entry

代码以上的打印:

modify=20110723201710;perm=el;size=4096;type=dir;unique=807g4e5a5; tests
modify=20111206092323;perm=el;size=4096;type=dir;unique=807g1008e0; .xchat2
modify=20111022125631;perm=el;size=4096;type=dir;unique=807g10001a; .gconfd
modify=20110808185618;perm=el;size=4096;type=dir;unique=807g160f9a; .skychart
...

从python3.3,ftplib将提供一个具体的方法来这样做:

我试图获取文件名,最后修改的邮票,文件大小等,并希望添加我的代码时,我找到了自己的方式。编写循环来解析 ftp.dir(dir_list.append)只花了几分钟时间利用python std lib之类的东西,比如 strip()(来清理文本行)和 split()来创建数组。

ftp = FTP('sick.domain.bro')
ftp.login()
ftp.cwd('path/to/data')

dir_list = []
ftp.dir(dir_list.append)

# main thing is identifing which char marks start of good stuff
# '-rw-r--r--   1 ppsrt    ppsrt      545498 Jul 23 12:07 FILENAME.FOO
#                               ^  (that is line[29])

for line in dir_list:
   print line[29:].strip().split(' ') # got yerself an array there bud!
   # EX ['545498', 'Jul', '23', '12:07', 'FILENAME.FOO']

LIST 响应的布局没有标准。您必须编写代码来处理最流行的布局。我将从Linux ls 和Windows Server DIR 格式开始。不过,那里有很多种类。

如果无法解析较长的列表,请回退到 nlst 方法(返回 NLST 命令的结果)。对于奖励积分,作弊:可能包含已知文件名的行中最长的数字是其长度。

我碰巧遇到了似乎不支持MLSD的FTP服务器(Rackspace Cloud Sites虚拟服务器)。然而,我需要几个文件信息字段,例如大小和时间戳,而不仅仅是文件名,所以我必须使用DIR命令。在这台服务器上,DIR的输出看起来非常像OP。如果它对任何人有帮助,这里有一个Python类,它解析一行这样的输出以获取文件名,大小和时间戳。

导入日期时间

class FtpDir:
    def parse_dir_line(self, line):
        words = line.split()
        self.filename = words[8]
        self.size = int(words[4])
        t = words[7].split(':')
        ts = words[5] + '-' + words[6] + '-' + datetime.datetime.now().strftime('%Y') + ' ' + t[0] + ':' + t[1]
        self.timestamp = datetime.datetime.strptime(ts, '%b-%d-%Y %H:%M')

我知道,不是很便携,但很容易扩展或修改以处理各种不同的FTP服务器。

这是来自Python文档

>>> from ftplib import FTP_TLS
>>> ftps = FTP_TLS('ftp.python.org')
>>> ftps.login()           # login anonymously before securing control 
channel
>>> ftps.prot_p()          # switch to secure data connection
>>> ftps.retrlines('LIST') # list directory content securely
total 9
drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .
drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..
drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin
drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc
d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming
drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib
drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub
drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr
-rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg

这帮助了我的代码。

当我尝试仅焚烧一种类型的文件并通过添加测试每行的条件在屏幕上显示它们时。

喜欢这个

elif command == 'ls':
    print("directory of ", ftp.pwd())
    data = []
    ftp.dir(data.append)

    for line in data:
        x = line.split(".")
        formats=["gz", "zip", "rar", "tar", "bz2", "xz"]
        if x[-1] in formats:
            print ("-", line)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top