Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I'm utilizing ftplib to associate with a ftp site. I need to get the most as of late transferred record and download it. I'm ready to interface with the ftp worker and list the documents, I additionally have placed them in elite and got the datefield changed over. Is there any function/module which can get the recent date and yield the entire line from the list?

#!/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','[email protected]')

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

Resolved:

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

One issue, is it conceivable to recover the main component from the dictionary? what I did here is that the for loop runs just a single time and exits subsequently giving me the initially sorted value which is fine, yet I don't think it is a decent practice to do it thusly..

1 Answer

0 votes
by (26.4k points)

You can use sorted method with NLST. Try the following code:

ftp = FTP(host="127.0.0.1", user="u",passwd="p")

ftp.cwd("/data")

file_name = sorted(ftp.nlst(), key=lambda x: ftp.voidcmd(f"MDTM {x}"))[-1]

Are you looking for a good python tutorial? Join the python online course fast and gain more knowledge in python.

Related questions

0 votes
1 answer
asked Nov 27, 2020 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
1 answer
asked Aug 4, 2020 in AWS by Amyra (12.9k points)
0 votes
1 answer
asked Aug 4, 2020 in AWS by Amyra (12.9k points)
0 votes
1 answer
asked Aug 4, 2020 in AWS by Amyra (12.9k points)

Browse Categories

...