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 error message: WindowsError: [Error 3] The system cannot find the path specified: '/test123/*.*'
Do someone have an idea how to resolve this issue? Thank you in advance!
import os, time
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
path = 'test123'
print 'Changing to:' + path
ftp.cwd(path)
files = ftp.retrlines('LIST')
print 'List of Files:' + files
#--everything works fine until here!...
#--The Logic which shall delete the files after the are 7 days old--
now = time.time()
for f in os.listdir(path):
if os.stat(f).st_mtime < now - 7 * 86400:
if os.path.isfile(f):
os.remove(os.path.join(path, f))
except:
exit ("Cannot delete files")
print 'Closing FTP connection'
ftp.close()
What OS are you running on? The file path
/test123/*.*
is Unix-style yet the message saysWindowsError
. Are you taking the output of an ftp LIST command, which is in Unix-style, and trying to use it verbatim in a Windows script?Well, it looks like the error you are seeing has to do with the fact that you are trying to remove the 'test123' directory from your local machine, not the FTP site. The FTP docs have a method called delete, and that's what you'd want to use to remove the file. As far as testing whether or not something is 7 days old or not, you might actually have to pull those files down from the FTP temporarily then check the modify times before using FTP.delete.
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.
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.
OK. Assuming your FTP server supports the
MLSD
command, make a module with the following code (this is code from a script I use to sync a remote FTP site with a local directory):module code
single directory case
If you want to work on the files of a directory, you can:
This should do what you want.
a directory and its descendants
Now, if this should work recursively, you'll have to do the following two changes in the code for “single directory case”:
and
Possible caveat
The servers I've worked with didn't have any issues with relative paths in the
STOR
andDELE
commands, sosite.delete
with a relative path worked too. If your FTP server requires pathless filenames, you should first.cwd
to thepath
provided,.delete
the plainftpfile.name
and then.cwd
back to the base folder.I had to do this and it took a while, thought I could save someones time here. We are using python with ftputil module installed: