How to delete files with a Python script from a FTP server which are older than 7 days?

前端 未结 5 1662
遥遥无期
遥遥无期 2020-12-03 15:25

I would like to write a Python script which allows me to delete files from a FTP Server after they have reached a certain age. I prepared the scipt below but it throws the e

5条回答
  •  忘掉有多难
    2020-12-03 16:01

    OK, well rather than analyze the code you have posted any further, here's an example instead that might put you on the right track.

    from ftplib import FTP
    import re
    
    pattern = r'.* ([A-Z|a-z].. .. .....) (.*)'
    
    def callback(line):
        found = re.match(pattern, line)
        if (found is not None):
            print found.groups()
    
    ftp = FTP('myserver.wherever.com')
    ftp.login('elvis','presley')
    ftp.cwd('testing123')
    ftp.retrlines('LIST',callback)
    
    ftp.close()
    del ftp
    

    Run it and you'll get output something like this, which should be a start towards what you're trying to achieve. To finish it out you'd need to parse the first result into a datetime, compare it with "now" and use ftp.delete() to get rid of the remote file if it's too old.

    >>> 
    ('May 16 13:47', 'Thumbs.db')
    ('Feb 16 17:47', 'docs')
    ('Feb 23  2007', 'marvin')
    ('May 08  2009', 'notes')
    ('Aug 04  2009', 'other')
    ('Feb 11 18:24', 'ppp.xml')
    ('Jan 20  2010', 'reports')
    ('Oct 10  2005', 'transition')
    >>> 
    

提交回复
热议问题