使用python备份文件
想写个定时备份文件的功能,这个功能需要实现:
1.搜索指定的目录里是否存在当天的文件
2.如果存在压缩并加密文件
3.通过ftp上传到备份服务器
4.在备份服务器上定时将文件拷贝到移动硬盘并定时清理文件
1.搜索指定目录
import glob import os import shutil class FileHelper: def __init__(self, searchdir, searchstr): self.dir = searchdir self.searchstr = searchstr def get_sourcefile(self): sourcepath = ("{searchdir}\*{searchstr}*".format(searchdir=self.dir, searchstr=self.searchstr)) return glob.glob(sourcepath) @staticmethod def get_destfile(sourcefile, destdir): tail = os.path.split(sourcefile)[1] return os.path.join(destdir, tail[:tail.rfind('.')] + '.zip') @staticmethod def get_shortfilename(sourcefile, destdir): tail = os.path.split(sourcefile)[1] return os.path.join(destdir, tail) @staticmethod def copyfile(sourcefilename, destfilename): shutil.copyfile(sourcefilename, destfilename) @staticmethod def deletefile(filename): os.remove(filename)
2.压缩文件
本来想通过Python自带的zipfile类来实现的,如下代码所示。
import zipfile class Zip(object): def __init__(self, sourcefilename, destfilename, password): self.sourcefilename = sourcefilename self.destfilename = destfilename self.password = password def zip(self): azip = zipfile.ZipFile(self.destfilename, 'w') azip.setpassword(self.password.encode('utf-8')) azip.write(self.sourcefilename)
结果生成的压缩文件,不用密码都可以打开,查了Python的文档才知道zipFile.
setpassword
(pwd)
Set pwd as default password to extract encrypted files.
这个密码是用来解压文件时候用的,至于压缩文件的时候怎么设置密码,就不知道了。。。
所以退而求其次,用7zip的命令行方式了
import os class Zip(object): def __init__(self, sourcepath, destpath, password): self.sourcepath = sourcepath self.destpath = destpath self.password = password def zipfile(self): pipe = os.popen("7z a -tzip {destpath} -p{password} {sourcepath}".format(destpath=self.destpath, password=self.password, sourcepath=self.sourcepath)) pipe.read() pipe.close()
3.上传FTP
import ftplib class FileUpaloder: def __init__(self, host, username, password, localfile, remotefile): self.host = host self.username = username self.password = password self.localfile = localfile self.remotefile = remotefile def upload(self): f = ftplib.FTP(self.host) f.login(self.username, self.password) bufsize = 1024 fp = open(self.localfile, 'rb') f.storbinary('STOR ' + self.remotefile, fp, bufsize) fp.close() f.quit()
4.备份并定时清理文件
from filehelper import * import datetime sourcepath = "C:\\source" destpath = "C:\\source\\backup" searchstr = "aa" FileHelper = FileHelper(sourcepath, searchstr) sourcefilelist = FileHelper.get_sourcefile() # 备份文件 for filename in sourcefilelist: destfilename = FileHelper.get_destfile(filename, destpath) datestr = datetime.date.today().strftime("%Y_%m_%d") if filename in datestr: FileHelper.copyfile(filename, destfilename) # 删除文件 for filename in sourcefilelist: datestr = filename[13:23] filedate = datetime.datetime.strptime(datestr, "%Y_%m_%d") checkDate = datetime.date.today() - datetime.timedelta(days=10) if filedate <= checkDate: FileHelper.deletefile(filename)