pilgrim773 wrote:
Hello I am new to Python programming. I need a write a script which
will delete files from a FTP server after they have reached a certain
age, like 7 days for example. I have prepared this code below, but I
get an error message:
The system cannot find the path specified: '/test123/*.*' Probably
someone can help me further? Thank you in advance!
import os, time, ftputil
from ftplib import FTP
ftp = FTP('127.0.0.1')
print "Automated FTP Maintainance"
print 'Logging in.'
ftp.login('admin', 'admin')
# This is the directory that we want to go to
directory = 'test123'
print 'Changing to:' + directory
ftp.cwd(directory)
files = ftp.retrlines('LIST')
print 'List of Files:' + files
# ftp.remove('LIST')
It's better to pass the full filename instead of changing the directory
because it means that you don't need to keep track of which directory
you're currently in, for example:
files = ftp.retrlines(directory + '/LIST')
#-------------------------------------------
now = time.time()
for f in os.listdir(directory):
if os.stat(f).st_mtime < now - 7 * 86400:
if os.directory.isfile(f):
os.remove(os.directory.join(directory, f))
The os module works with _local_ files, not the remote files on a
server.
You can list the files and get info about them like this:
reply = []
ftp.retrlines("LIST " + directory, reply.append)
'reply' will be a list of lines, one per file, which you can then parse.
It shouldn't be too difficult to write a function to hide the messy
details. :-)
#except:
#exit ("Cannot delete files")
Bare excepts are almost always a very bad idea.
#-------------------------------------------
print 'Closing FTP connection'
ftp.close()
--
http://mail.python.org/mailman/listinfo/python-list