欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-02 18:33:29
文件备份,使用Python3对zip文件进行处理。Python使用zipfile进行简单备份。 # !/usr/bin/python3 # coding:utf-8 #...

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

# !/usr/bin/python3
# coding:utf-8
# Filename: backup_ver1.py
import 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')