Python FTP按日期获取最新文件

时间:2012-01-24 16:42:41

标签: python linux ftp ftplib

我使用ftplib连接到ftp站点。我想获取最近上传的文件并下载它。我能够连接到ftp服务器并列出文件,我也将它们放在一个列表中并转换datefield。是否有任何函数/模块可以获取最近的日期并从列表中输出整行?

#!/usr/bin/env python

import ftplib
import os
import socket
import sys


HOST = 'test'


def main():
    try:
        f = ftplib.FTP(HOST)
    except (socket.error, socket.gaierror), e:
        print 'cannot reach to %s' % HOST
        return
    print "Connect to ftp server"

    try:
        f.login('anonymous','al@ge.com')
    except ftplib.error_perm:
        print 'cannot login anonymously'
        f.quit()
        return
    print "logged on to the ftp server"

    data = []
    f.dir(data.append)
    for line in data:
        datestr = ' '.join(line.split()[0:2])
        orig-date = time.strptime(datestr, '%d-%m-%y %H:%M%p')


    f.quit()
    return


if __name__ == '__main__':
    main()

解决:

data = []
f.dir(data.append)
datelist = []
filelist = []
for line in data:
    col = line.split()
    datestr = ' '.join(line.split()[0:2])
    date = time.strptime(datestr, '%m-%d-%y %H:%M%p')
    datelist.append(date)
    filelist.append(col[3])

combo = zip(datelist,filelist)
who = dict(combo)

for key in sorted(who.iterkeys(), reverse=True):
   print "%s: %s" % (key,who[key])
   filename = who[key]
   print "file to download is %s" % filename
   try:
       f.retrbinary('RETR %s' % filename, open(filename, 'wb').write)
   except ftplib.err_perm:
       print "Error: cannot read file %s" % filename
       os.unlink(filename)
   else:
       print "***Downloaded*** %s " % filename
   return

f.quit()
return

一个问题是,是否可以从字典中检索第一个元素?我在这里做的是for循环只运行一次并退出,从而给我第一个排序的值,这很好,但我不认为以这种方式这样做是好的做法..

5 个答案:

答案 0 :(得分:7)

为什么不使用下一个dir选项?

ftp.dir('-t',data.append)

使用此选项,文件列表按时间顺序从最新到最旧。然后只需检索列表中的第一个文件即可下载。

答案 1 :(得分:3)

对于那些寻求在文件夹中查找最新文件的完整解决方案的人:

MLSD

如果您的FTP服务器支持MLSD命令,则解决方案很简单:

entries = list(ftp.mlsd())
entries.sort(key = lambda entry: entry[1]['modify'], reverse = True)
latest_name = entries[0][0]
print(latest_name)

列表

如果您需要使用过时的LIST命令,则必须解析它返回的专有列表。

常见的* nix列表如下:

-rw-r--r-- 1 user group           4467 Mar 27  2018 file1.zip
-rw-r--r-- 1 user group         124529 Jun 18 15:31 file2.zip

使用这样的清单,此代码即可:

from dateutil import parser

# ...

lines = []
ftp.dir("", lines.append)

latest_time = None
latest_name = None

for line in lines:
    tokens = line.split(maxsplit = 9)
    time_str = tokens[5] + " " + tokens[6] + " " + tokens[7]
    time = parser.parse(time_str)
    if (latest_time is None) or (time > latest_time):
        latest_name = tokens[8]
        latest_time = time

print(latest_name)

这是一种相当脆弱的方法。


MDTM

一种更可靠但效率更低的方法是使用MDTM命令来检索单个文件/文件夹的时间戳:

names = ftp.nlst()

latest_time = None
latest_name = None

for name in names:
    time = ftp.voidcmd("MDTM " + name)
    if (latest_time is None) or (time > latest_time):
        latest_name = name
        latest_time = time

print(latest_name)

非标准-t开关

某些FTP服务器支持用于-t(或NLST)命令的专有非标准LIST开关。

lines = ftp.nlst("-t")

latest_name = lines[-1]

请参见How to get files in FTP folder sorted by modification time


下载找到的文件

无论使用哪种方法,一旦拥有latest_name,您都可以将其下载为任何其他文件:

file = open(latest_name, 'wb')
ftp.retrbinary('RETR '+ latest_name, file.write)

另请参见

答案 2 :(得分:3)

使用NLST,就像Martin Prikryl的回应: 您应该使用排序方法:

<ngb-pagination (pageChange)="onPageChange($event)" [collectionSize]="this.totalPosts" *ngIf="!this.mobile"
          [(page)]="this.currentPage" [boundaryLinks]="true"></ngb-pagination>

答案 3 :(得分:1)

如果您的所有日期都在time.struct_timestrptime会给您这个),那么您只需sort列表即可。

以下是一个例子:

#!/usr/bin/python

import time

dates = [
    "Jan 16 18:35 2012",
    "Aug 16 21:14 2012",
    "Dec 05 22:27 2012",
    "Jan 22 19:42 2012",
    "Jan 24 00:49 2012",
    "Dec 15 22:41 2012",
    "Dec 13 01:41 2012",
    "Dec 24 01:23 2012",
    "Jan 21 00:35 2012",
    "Jan 16 18:35 2012",
]

def main():
    datelist = []
    for date in dates:
        date = time.strptime(date, '%b %d %H:%M %Y')
        datelist.append(date)

    print datelist
    datelist.sort()
    print datelist

if __name__ == '__main__':
    main()

答案 4 :(得分:1)

我不知道你的ftp是怎么回事,但你的例子并不适合我。我更改了与日期排序部分相关的一些行:

    import sys
    from ftplib import FTP
    import os
    import socket
    import time

    # Connects to the ftp
    ftp = FTP(ftpHost)
    ftp.login(yourUserName,yourPassword)
    data = []
    datelist = []
    filelist = []
    ftp.dir(data.append)
    for line in data:
      col = line.split()
      datestr = ' '.join(line.split()[5:8])
      date = time.strptime(datestr, '%b %d %H:%M')
      datelist.append(date)
      filelist.append(col[8])
    combo = zip(datelist,filelist)
    who = dict(combo)
    for key in sorted(who.iterkeys(), reverse=True):
      print "%s: %s" % (key,who[key])
      filename = who[key]
      print "file to download is %s" % filename
      try:
        ftp.retrbinary('RETR %s' % filename, open(filename, 'wb').write)
      except ftplib.err_perm:
        print "Error: cannot read file %s" % filename
        os.unlink(filename)
      else:
        print "***Downloaded*** %s " % filename
    ftp.quit()