文件备份-Python3对文件夹下所有文件进行压缩处理

来源:互联网 发布:剑雨江湖数据晋级 编辑:程序博客网 时间:2024/06/05 11:55

文件备份,使用Python3对zip文件进行处理。Python使用zipfile进行简单备份。

# !/usr/bin/python3# coding:utf-8# Filename: backup_ver1.pyimport os,time,zipfile
def createZip(filePath,savePath,note = ''):    '''    将文件夹下的文件保存到zip文件中。    :param filePath: 待备份文件    :param savePath: 备份路径    :param note: 备份文件说明    :return:    '''    today = time.strftime('%Y%m%d')    now = time.strftime('%H%M%S')    fileList=[]    if not os.path.exists(today):        os.mkdir(today)        print('mkdir successful')    if len(note) == 0:        target = savePath + os.sep + today + os.sep + now + '.zip'    else:        target = savePath + os.sep + today + os.sep + now + '_' + note + '.zip'    newZip = zipfile.ZipFile(target,'w')    for dirpath,dirnames,filenames in os.walk(filePath):        for filename in filenames:            fileList.append(os.path.join(dirpath,filename))    for tar in fileList:        newZip.write(tar,tar[len(filePath):])#tar为写入的文件,tar[len(filePath)]为保存的文件名    newZip.close()    print('backup to',target)

def unZip(filePath,unzipPath):    '''    解压zip文件到指定路径    :param filePath: 待解压文件    :param unzipPath: 解压路径    :return:     '''    file = zipfile.ZipFile(filePath)    file.extractall(unzipPath)    print('unzip successfully to',unzipPath)
定义好函数之后,进行调用。
createZip(r'D:\01mine\06-Python\testZip',r'D:\01mine\06-Python')unZip(r'D:\01mine\06-Python\20171215\232717.zip',r'D:\01mine\06-Python\20171215\all')




阅读全文
0 0