Python入门题048文件夹生成zip(用shutil或zipfile)
题目:
使用 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()