0

I have this script to remove all images from a server directory:

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)

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

Thanks

  • 1
    Do you have to use python for this? The unix command `find` would be a much better solution. – John Gordon Oct 08 '16 at 15:49
  • 1
    Likely duplicate of [How to get FTP file's modify time using Python ftplib](http://stackoverflow.com/questions/29026709/how-to-get-ftp-files-modify-time-using-python-ftplib) – tdelaney Oct 08 '16 at 15:50

1 Answers1

0

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

So your code should be like this:

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 > older_date:
        ftp.delete(filename)

Note that mlsd command is not supported in every server.

More info available here:

https://docs.python.org/3/library/ftplib.html

https://www.rfc-editor.org/rfc/rfc3659.html

Community
  • 1
  • 1