Python实践练习:将一个文件夹备份到一个 ZIP 文件

题目

项目要求:假定你正在做一个项目,它的文件保存在 C:AlsPythonBook 文件夹中。你担心工作会丢失, 所以希望为整个文件夹创建一个 ZIP 文件, 作为“快照” 。你希望保存不同的版本, 希望 ZIP 文件的文件名每次创建时都有所变化。

代码

#! python3
# backupToZip.py - Copies an entire folder and its contents into
# a ZIP file whose filename increments.

import zipfile
import os


def backupToZip(folder):
    folder = os.path.abspath(folder)

    # 查找是否存在zip_N.zip,累加number
    number = 1
    while True:
        zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
        if not os.path.exists(zipFilename):
            break
        number = number + 1

    # 创建zip文件
    print('Creat %s...' % zipFilename)
    backupZip = zipfile.ZipFile(zipFilename, 'w')

    for root, dirs, files in os.walk(folder):
        print('Adding files in %s...' % root)
        backupZip.write(root.replace(folder, '.\'))

        for file in files:
            # 不包括已经打包的.zip文件
            newBase = os.path.basename(folder) + '_'
            if file.startswith(newBase) and file.endswith('.zip'):
                continue
            backupZip.write(os.path.join(root, file))
            print('    Adding %s' % file)

    backupZip.close()
    print('to_zip Done!')


backupToZip('D:\Code\VimCode\Python_auto\9_zip')

原文地址:https://www.cnblogs.com/wudongwei/p/9022109.html