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