For those who are looking for a complete solution to find the last file in a folder:
If your FTP server supports the MLSD command, the solution is easy:
entries = list(ftp.mlsd()) entries.sort(key = lambda entry: entry[1]['modify'], reverse = True) latest_name = entries[0][0] print(latest_name)
If you need to rely on the legacy LIST command, you need to parse the listing that it returns.
General 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
With such a list, this code will do:
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)
This is a rather fragile approach.
A more reliable but less efficient way is to use the MDTM to retrieve the timestamps of individual files / folders:
names = ftp.nlst() latest_time = None latest_name = None for name in names: time = ftp.sendcmd("MDTM " + name) if (latest_time is None) or (time > latest_time): latest_name = name latest_time = time print(latest_name)
Some FTP servers support their own custom -t switch for the NLST (or LIST ) command.
lines = ftp.nlst("-t") latest_name = lines[-1]
See Section How to get files in FTP folder sorted by modification time .
No matter which approach you use, as soon as you have the latest_name , you upload it like any other file:
file = open(latest_name, 'wb') ftp.retrbinary('RETR '+ latest_name, file.write)
See Also Getting the Last FTP Folder Name in Python .