1. 程式人生 > >使用python備份文件

使用python備份文件

__init__ sta 一個 ack 大型 color check 需要 定時清理

想寫個定時備份文件的功能,這個功能需要實現:
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)

使用python備份文件