I am trying to write a script to get the latest file from the latest sub- directory of FTP server in Python. My problem is I am unable to figure out the latest sub-directory. There are two options available, sub-directories have ctime available. Also in directory name date is mentioned that on which date directory was created. But I do not know how to get the name of the latest directory. I have figured out the following way (hoping for the server side to be sorted by latest ctime). I have done it the following way which will work if first object is the latest directory.
import ftplib
import os
import time
ftp = ftplib.FTP('test.rebex.net','demo', 'password')
ftp.cwd(str((ftp.nlst())[0])) #if directory is sorted in descending order by date.
But is there any way where I will find the exact directory by ctime or by date in directory name ?
Thanks a lot guys.
If your FTP server supports
MLSD
command, a solution is easy:If you want to base the decision on a modification timestamp:
If you want to use a file name:
If you need to rely on an obsolete
LIST
command, you have to parse a proprietary listing it returns.A common *nix listing is like:
With a listing like this, this code will do:
If you want to base the decision on a modification timestamp:
If you want to use a file name:
Some FTP servers may return
.
and..
entries inLIST
results. You may need to filter those.Partially based on: Python FTP get the most recent file by date.
If the folder does not contain any files, only subfolders, there are other easier options.
If you want to base the decision on a modification timestamp and the server supports non-standard
-t
switch, you can use:See How to get files in FTP folder sorted by modification time
If you want to use a file name: