专业的编程技术博客社区

网站首页 > 博客文章 正文

Python入门题048:文件夹生成zip(用shutil或zipfile)

baijin 2024-08-31 16:17:37 博客文章 7 ℃ 0 评论

题目:

使用 shutil 或 zipfile 对整个文件夹进行压缩,生成一个 zip 压缩包

#python #zip #shutil #压缩包

视频教程:

Python入门题048:文件夹生成zip(用shutil或zipfile)

代码1:

import shutil

dirname = '/private/var/www/coding-anderson/Python_100_Exercises/exercises_031_to_040'
shutil.make_archive('my_file', 'zip', dirname)


代码2:

import os
import zipfile

dirname = '/private/var/www/coding-anderson/Python_100_Exercises/exercises_031_to_040'


def zipdir(path, ziph: zipfile.ZipFile):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            if not file.endswith('.py'):
                continue
            abspath = os.path.join(root, file)
            ziph.write(abspath,
                       # 必须传入相对路径,
                       # 否则压缩包里的文件夹是从 /private 开始的
                       os.path.relpath(abspath,
                                       os.path.join(path, '..')))


zipf = zipfile.ZipFile('my_file.zip', 'w',
                       zipfile.ZIP_DEFLATED)
zipdir(dirname, zipf)
zipf.close()




Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表