Python FTP Latest File

How to determine the last modified file from the ftp directory list? I used the max function on the unix timestamp locally, but the ftp list is harder to parse. The contents of each line are separated by a space.

from ftplib import FTP
ftp = FTP('ftp.cwi.nl')
ftp.login()
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
    print line

exit:

drwxrwsr-x   5 ftp-usr  pdmaint     1536 Mar 20 09:48 .
dr-xr-srwt 105 ftp-usr  pdmaint     1536 Mar 21 14:32 ..
-rw-r--r--   1 ftp-usr  pdmaint     5305 Mar 20 09:48 INDEX
+3
source share
4 answers

Just make some corrections:

date_str = ' '.join(line.split()[5:8])
time.strptime(date_str, '%b %d %H:%M') # import time

And to find the latest file

for line in data:
    col_list = line.split()
    date_str = ' '.join(line.split()[5:8])
    if datePattern.search(col_list[8]):
        file_dict[time.strptime(date_str, '%b %d %H:%M')] = col_list[8]
        date_list = list([key for key, value in file_dict.items()])
s = file_dict[max(date_list)]
print s
+4
source

If the FTP server supports the command MLSD(and, quite possibly, does), you can use the class FTPDirectoryfrom which answers on the corresponding question.

ftplib.FTP (, aftp) FTPDirectory (, aftpdir), , .cwd aftpdir.getdata(aftp). :

import operator

max(aftpdir, key=operator.attrgetter('mtime')).name
+4

To analyze the date, you can use (since version 2.5):

datetime.datetime.strptime('Mar 21 14:32', '%b %d %H:%M')
+2
source

You can split each line and get the date:

date_str = ' '.join(line.split(' ')[5:8])

Then analyze the date (make sure that you can select egenix mxDateTime , in particular a function , to get comparable objects DateTimeFromString.

0
source

Source: https://habr.com/ru/post/1716121/


All Articles