使用python备份文件

想写个定时备份文件的功能,这个功能需要实现:
1.搜索指定的目录里是否存在当天的文件
2.如果存在压缩并加密文件
3.通过ftp上传到备份服务器
4.在备份服务器上定时将文件拷贝到移动硬盘并定时清理文件

本来想通过BAT文件批处理做,无奈水平有限,这BAT的语法实在玩不来。。。正好前几天图书打折囤了几本python的书,就想用Python试试看,折腾两三个小时,总算搞定了,在这里备份一下。
Python的语法有些怪异的,类的实例方法第一个入参要写self,应该类似于C#,Java里的this,问题是其他语言都是编译器给默认加一个this,它这个要码农自己码上一个self。
C#,Java用分号表示语句的结束,Python省事了 不用分号了,这个倒是像VB.
更诡异的是 语句块,C#和Java用{}包括,VB的if至少有个endif表示结束,python比较神奇,直接用代码的缩进表示,这下好了,代码的缩进不止是代码美观的问题了,还有语法含义,这样写出来的代码应该看上去至少是整齐划一的,不整齐语义都不对了。。。
当然了 这些只是语言风格的问题,没什么好与坏,习惯了就好了。
单纯从这个脚本小功能来说,Python用起来还是蛮顺手的,Pycharm这个IDE也是蛮好用的,当然了,这个只是这个微不足道的小功能来说,大型的功能开发就不知道了。

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)

猜你喜欢

转载自www.cnblogs.com/Farseer1215/p/9579655.html