我想编写一个 Python 脚本,允许我在文件达到一定期限后从 FTP 服务器中删除文件。我准备了下面的脚本,但它抛出了错误消息:WindowsError: [Error 3] The system cannot find the path specified: '/test123/*.*'
有人知道如何解决这个问题吗?提前致谢!
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()
最佳答案
好的。假设您的 FTP 服务器支持 MLSD
命令,使用以下代码创建一个模块(这是我用来将远程 FTP 站点与本地目录同步的脚本中的代码):
模块代码
# for python ≥ 2.6
import sys, os, time, ftplib
import collections
FTPDir= collections.namedtuple("FTPDir", "name size mtime tree")
FTPFile= collections.namedtuple("FTPFile", "name size mtime")
class FTPDirectory(object):
def __init__(self, path='.'):
self.dirs= []
self.files= []
self.path= path
def getdata(self, ftpobj):
ftpobj.retrlines('MLSD', self.addline)
def addline(self, line):
data, _, name= line.partition('; ')
fields= data.split(';')
for field in fields:
field_name, _, field_value= field.partition('=')
if field_name == 'type':
target= self.dirs if field_value == 'dir' else self.files
elif field_name in ('sizd', 'size'):
size= int(field_value)
elif field_name == 'modify':
mtime= time.mktime(time.strptime(field_value, "%Y%m%d%H%M%S"))
if target is self.files:
target.append(FTPFile(name, size, mtime))
else:
target.append(FTPDir(name, size, mtime, self.__class__(os.path.join(self.path, name))))
def walk(self):
for ftpfile in self.files:
yield self.path, ftpfile
for ftpdir in self.dirs:
for path, ftpfile in ftpdir.tree.walk():
yield path, ftpfile
class FTPTree(FTPDirectory):
def getdata(self, ftpobj):
super(FTPTree, self).getdata(ftpobj)
for dirname in self.dirs:
ftpobj.cwd(dirname.name)
dirname.tree.getdata(ftpobj)
ftpobj.cwd('..')
单目录案例
如果你想处理一个目录的文件,你可以:
import ftplib, time
quite_old= time.time() - 7*86400 # seven days
site= ftplib.FTP(hostname, username, password)
site.cwd(the_directory_to_work_on) # if it's '.', you can skip this line
folder= FTPDirectory()
folder.getdata(site) # get the filenames
for path, ftpfile in folder.walk():
if ftpfile.mtime < quite_old:
site.delete(ftpfile.name)
这应该做你想做的。
目录及其后代
现在,如果这应该以递归方式工作,您必须在“单目录情况”的代码中进行以下两处更改:
folder= FTPTree()
和
site.delete(os.path.join(path, ftpfile.name))
可能的警告
我使用过的服务器在 STOR
和 DELE
命令中没有任何相对路径问题,所以 site.delete
使用相对路径也有效。如果您的 FTP 服务器需要无路径文件名,您应该首先 .cwd
到提供的 path
,.delete
普通的 ftpfile.name
然后 .cwd
回到基本文件夹。
关于python - 如何使用 Python 脚本从 FTP 服务器中删除超过 7 天的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2867217/