想写个定时备份文件的功能,这个功能需要实现:
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)

使用python备份文件的更多相关文章

  1. python 备份文件脚本

    使用python备份服务器的文件 #coding=utf- import os import os.path def copyFiles(sourceDir, targetDir): for file ...

  2. python简要

    python用冒号代替{}开启语句块 /usr/bin/python 加在脚本的头部, ./脚本 help("str") : 查看命令帮助 '''三引号可以打印换行字符串 prin ...

  3. python第四篇:linux命令行总结 + 自动备份Python程序

    由于最近需要学习Python爬虫相关的知识,所以就先从Python基础.Linux基础开始进行了学习,下面主要是总结了常见的Linux的命令行.最后为了巩固学到的东西,尝试写了个自动备份的Python ...

  4. Python 实例: 备份文件

    都说生命苦短,我用python, 所以这两天我也开始学python了. 昨天搞了下语法,今天搞出来个实例,备份文件.尽管编码相当烂,但是测试了一下,还真能用. 它读取一个任务文件, 根据指定的任务参数 ...

  5. 利用Python爆破数据库备份文件

    某次测试过程中,发现PHP备份功能代码如下: // 根据时间生成备份文件名 $file_name = 'D' . date('Ymd') . 'T' . date('His'); $sql_file_ ...

  6. python小程序:备份文件

    设计程序,有以下步骤: 需要备份的文件和目录由一个列表指定. 备份应该保存在主备份目录中. 文件备份成一个zip文件. zip存档的名称是当前的日期和时间. 解决方案: 版本一: #!/usr/bin ...

  7. 备份文件的python脚本(转)

    作用:将目录备份到其他路径.实际效果:假设给定目录"/media/data/programmer/project/python" ,备份路径"/home/diegoyun ...

  8. 配置百度云盘python客户端bypy上传备份文件

    要求:安装python2.7,安装git 1.git clone https://github.com/houtianze/bypy.git 2.cd bypy 3.sudo python setup ...

  9. python 项目实战之备份文件夹并且压缩文件夹及下面的文件

    #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/11/12 14:21 # @Author : zoulixiang # @S ...

随机推荐

  1. Unity 3D入门简介

    最近在刚开始学习Unity 3D,在这里记录一下学习心得和学习笔记,边学边写,可能会比较零散.好了,废话不多说,今天从Unity 3D入门写起,主要简要介绍一下Unity 3D的和一些学习资料.以下如 ...

  2. django ORM多对多操作

    创建多对多: 方式一:自定义关系表 class Host(models.Model): nid = models.AutoField(primary_key=True) hostname = mode ...

  3. 接口自动化 基于python+Testlink+Jenkins实现的接口自动化测试框架

    链接:http://blog.sina.com.cn/s/blog_13cc013b50102w94u.html

  4. 阿里云CentOS7服务器利用LVM分区挂载磁盘全记录

    1.进入服务器后,首先利用fdisk -l来观察磁盘信息,可以看出红线标注处,有两块硬盘信息,分别是40G和300G 2.同时你也可以观察到分区信息,40G的硬盘已经分了一个区vda1,大小(Bloc ...

  5. 和2018年年初做管理系统的不同(vuex)

    从2017年底开始做公司批改后台系统(服务内部人员对熊猫小课用户的作业进行批改.对批改员工资结算等)到教务系统(服务于内部人员对熊猫小课等移动端产品的内容进行配置等).ai-boss系统(服务于内部人 ...

  6. java.util.concurrent包下并发锁的特点与适用场景

    序号 类 备注 核心代码 适用场景 1 synchronized 同步锁 并发锁加在方法级别上,如果是单例class对象,则只能允许一个线程进入public synchronized void doX ...

  7. Kong(V1.0.2) Securing the Admin API

    Introduction Kong的Admin API为Services, Routes, Plugins, Consumers, and Credentials的管理和配置提供了一个RESTful接 ...

  8. python3 模拟鼠标和键盘操作

    1. 安装pyperclip pip install pyperclip 使用方法复制 pyperclip.copy("hello world") 粘贴 pyperclip.pas ...

  9. C++常用数据结构-CString

    CString类Str.format(_T(“%d”),number)例子: str.Format(_T("%d"),number);%c 单个字符(char)%d 十进制整数(i ...

  10. Python对wav文件的重采样

    例如从2channel,4.41k hz 重采样到 1 channel,16k hz def downsampleWav(src, dst, inrate=44100, outrate=16000, ...