项目:将一个文件夹备份到一个ZIP文件

# 项目:将一个文件夹备份到一个ZIP文件
#! python3
# backupToZip.py - Copies an entire folder and its contents into a ZIP file whose filename increments.

import zipfile,os

# 定义函数
def backupToZip(folder):
    # Backup the entire contents of 'folder' into a ZIP file.

    folder = os.path.abspath(folder)  # make sure folder is absolute

    # Figure out the filename this code should use based on
    # What files already exists
    number = 1
    while True:
        zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'  # 返回path最后的文件名
        if not os.path.exists(zipFilename):
            break
        number += 1
    # TODO: Create the ZIP file.
    print('Create %s ...' % zipFilename)
    backupZip = zipfile.ZipFile(zipFilename, 'w')

    # TODO: Walk the entire folder tree and compress this files in each folder.
    for foldername, subfolders, filenames in os.walk(folder):
        print('Adding files in %s ...' % foldername)
        # Add the current folder to the ZIP file.
        backupZip.write(foldername)
        for filename in filenames:
            newBase = os.path.basename(folder) + '_'
            if filename.startswith(newBase) and filename.endswith('.zip'):
                continue  # don't backup the backup ZIP files
            backupZip.write(os.path.join(foldername, filename))
    backupZip.close()

# 调用函数
backupToZip('E:\\Pycharm\\code\\Class')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值