Python: remove files older than X days
<p>I have this script to remove all images from a server directory:</p>

<pre><code>import ftplib
ftp = ftplib.FTP("server", "user", "pass")
files = ftp.dir('/')
ftp.cwd("/html/folder/")

filematch = '*.jpg'
target_dir = '/html/folder'
import os

for filename in ftp.nlst(filematch):
ftp.delete(filename)
</code></pre>

<p>Any advice on how to add a filter for the file match "older than three days"?</p>

<p>Thanks </p>

<p>In python 3.3+ was added <code>mlsd</code> command support, which allows you to get the <code>facts</code> as well as list the directory.</p>

<p>So your code should be like this:</p>

<pre><code>filematch = '.jpg'
target_dir = '/html/folder'
import os

for filename, create, modify in ftp.mlsd(target_dir, facts=['create', 'modify']):
    if filename.endswith(file_match) and create &gt; older_date:
        ftp.delete(filename)
</code></pre>

<p>Note that <code>mlsd</code> command is not supported in every server.</p>

<p>More info available here:</p>

<p><a href="https://docs.python.org/3/library/ftplib.html" rel="nofollow">https://docs.python.org/3/library/ftplib.html</a></p>

<p><a href="https://tools.ietf.org/html/rfc3659.html" rel="nofollow">https://tools.ietf.org/html/rfc3659.html</a> </p>

python ftp