1

I'm trying to navigate to the latest directory on an FTP site to download a CSV file in it. For this example, I'm trying to select the OG_EWA_2018-06-02 link. How can I access using the max date? Thanks

OG_EWA_2018-03-02 . . . Mar 02 10:52        
OG_EWA_2018-04-03 . . . Apr 03 09:20        
OG_EWA_2018-05-02 . . . May 02 09:17        
OG_EWA_2018-06-02 . . . Jun 02 10:52 
from ftplib import FTP

ftp = FTP('ftp')
ftp.cwd('OG_EWA')
ftp.retrlines('LIST')
print(ftp)
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992

1 Answers1

1

The first thing you need to do is to get the output into a list or something else you can process it, instead of just dumping it to stdout. As the docs explain, you do this by passing a callback function:

files = []
ftp.retrlines('LIST', files.append)

Now, you’ve got a list of lines. Since the filenames are identical up to the date, and the date is in YYYY-MM-DD format, the normal string order is the date order, so you don’t need to do anything fancy; just call max on it:

latest = max(files)
abarnert
  • 354,177
  • 51
  • 601
  • 671