您可以使用FTPLIB在Python中充分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服务器可能格式化这个名单。
有没有一种可移植的方式来获得充满目录列表的阵列?
(数组应该只有该文件夹的名称。)
Answer 1:
尝试使用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
Answer 2:
解析FTP目录列表可靠/标准化的方法是使用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
...
从蟒蛇3.3开始,FTPLIB将提供一个具体的方法来做到这一点:
- http://bugs.python.org/issue11072
- http://hg.python.org/cpython/file/67053b135ed9/Lib/ftplib.py#l535
Answer 3:
还有的布局没有标准的LIST
响应。 你必须编写代码来处理最流行的布局。 我与Linux的启动ls
和Windows Server DIR
格式。 有很多各种各样的摆在那里,虽然。
回落到nlst
方法(返回的结果NLST
命令),如果你无法分析更长的名单。 对于加分,欺骗:也许包含已知的文件名行最长的号码是其长度。
Answer 4:
我发现我的方式在这里尝试获取文件名,最后修改邮票,文件大小等,并希望增加我的代码。 只用了几分钟的时间来写一个循环来解析ftp.dir(dir_list.append)
利用Python的标准库的东西像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']
Answer 5:
我碰巧与FTP服务器(Rackspace公司云网站虚拟服务器)似乎并不支持MLSD被卡住。 然而,我需要的文件信息的几个领域,如大小和时间戳,而不仅仅是文件名,所以我必须使用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服务器。
Answer 6:
这是从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
Answer 7:
这帮助我与我的代码。
当我试图feltering只是一个类型的文件,并通过在每行测试加入条件让他们在屏幕上。
像这样
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)
文章来源: Using Python's ftplib to get a directory listing, portably