Muzamal Rana
Muzamal Rana

Reputation: 135

Python FTP server download Latest File with specific keywords in filename

I want to download the most recent file from FTP server with python. I am able to connect to the server and download all the files in a particular directory but I do not know how to find the most recent file with the specific keyword in the subject.

Following is the code i am using. But it returns all the files with *.png keyname. I do not know how to apply os.path.getctime here to get the latest file.Thats all the help i wanted.

        import ftplib
        import os

        ftp = ftplib.FTP('test.rebex.net', 'demo','password')
        ftp.retrlines('LIST')

        ftp.cwd("/pub")

        ftp.retrlines('LIST')

        ftp.cwd("example")

        ftp.retrlines('LIST')
        filematch='*.png'
        target_dir='C:/Users/muzamal.pervez/Desktop/OPD Claims'
        for filename in ftp.nlst(filematch):
            target_file_name = os.path.join(target_dir,os.path.basename(filename))
            with open(target_file_name,'wb') as fhandle:
                    ftp.retrbinary('RETR %s' %filename, fhandle.write)

Upvotes: 0

Views: 2961

Answers (1)

Muzamal Rana
Muzamal Rana

Reputation: 135

resolved.

    import ftplib
    import os
    import time
    from dateutil import parser

    ftp = ftplib.FTP('test.rebex.net', 'demo','password')
    ftp.retrlines('LIST')

    ftp.cwd("pub")
    ftp.cwd("example")
    ftp.retrlines('LIST')

    names = ftp.nlst()
    final_names= [line for line in names if 'client' in line]

    latest_time = None
    latest_name = None

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

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

Upvotes: 2

Related Questions