当前位置: 移动技术网 > IT编程>脚本编程>Python > 文件备份:Python3对文件夹下所有文件进行压缩处理

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

2017年12月18日  | 移动技术网IT编程  | 我要评论

扬州网址大全,弱碱性水杯,mbc演艺大赏2016

文件备份,使用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')

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网