Python ftplib, get the latest file via ftp
<p>I know how to set to download a file like this, but most files aren't named file-LATEST. How would I be able to download the latest file?</p>

<p>via:</p>

<ul>
<li>date modified</li>
<li>timestamp</li>
<li><code>if version.current &lt; version.new then download</code></li>
</ul>

<p>Here's what I have so far:</p>

<pre><code>#!/usr/bin/env python

import ftplib
import os
import socket

HOST = 'ftp.site.org'
DIRN = 'dir/'
FILE = 'filename-LATEST.tar.gz'

def main():
    try:
    f = ftplib.FTP(HOST)
except (socket.error, socket.gaierror), e:
    print 'ERROR: cannot reach "%s"' % HOST
    return
print '*** Connected to host "%s"' % HOST

try:
    f.login()
except ftplib.error_perm:
    print 'ERROR:: cannot login anonymously'
    f.quit()
    return
print '*** Logged in as "anonymous"'

try:
    f.cwd(DIRN)
except ftplib.error_perm:
    print 'ERROR: cannot CD to "%s"' % DIRN
    f.quit()
    return
print '*** Changed to "%s" folder' % DIRN

try:
    f.retrbinary('RETR %s' % FILE, open(FILE, 'wb').write)
except ftplib.error_perm:
    print 'ERROR: cannot read file "%s"' % FILE
    os.unlink(FILE)
else:
    print '*** Downloaded "%s" to CWD' % FILE
f.quit()
return

if __name__ == '__main__':
main()
</code></pre>
