首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >python 压缩文件夹 脚本

python 压缩文件夹 脚本

作者头像
用户5760343
发布2022-05-13 17:59:56
发布2022-05-13 17:59:56
1.6K00
代码可运行
举报
文章被收录于专栏:sktjsktj
运行总次数:0
代码可运行

! 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.

代码语言:javascript
代码运行次数:0
运行
复制
folder = os.path.abspath(folder) # make sure folder is absolute

# Figure out the filename this code should used based on
# what files already exist.
number = 1
while True:
    zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
    if not os.path.exists(zipFilename):
        break
    number = number + 1

# Create the zip file.
print('Creating %s...' % (zipFilename))
backupZip = zipfile.ZipFile(zipFilename, 'w')

# Walk the entire folder tree and compress the 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)

    # Add all the files in this folder to the ZIP file.
    for filename in filenames:
        if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):
            continue # don't backup the backup ZIP files
        backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')

backupToZip('d:\WelcomeToWangsu')

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ! python3
  • backupToZip.py
  • Copies an entire folder and its contents into
  • a zip file whose filename increments.
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档