python zip压缩_Python 使用zipfile压缩目录

zipfile

zipfile.ZipFile

zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None)

复制代码file: 生成压缩文件所在的路径

mode: r, w, a, x

compression: ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA

compresslevel: When using ZIP_STORED or ZIP_LZMA it has no effect.

When using ZIP_DEFLATED integers 0 through 9 are accepted (see zlib for more information). When using ZIP_BZIP2 integers 1 through 9 are accepted (see bz2 for more information).

Zipfile.write

ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None)

复制代码filename: 即将被压缩的文件路径

arcname: 归档文件路径

If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry

Note Archive names should be relative to the archive root, that is, they should not start with a path separator.

Note If arcname (or filename, if arcname is not given) contains a null byte, the name of the file in the archive will be truncated at the null byte.

code

场景:将source目录中的所有文件打包压缩命名为compress_complete.zip并放入target目录下

project

└───source

│ └── file1.md

│ └── file2.md

│ └── file3.md

└───target

└── compress_complete.zip

复制代码import os

import zipfile

source_dir = '/project/source' (pwd查看绝对路径替换)

zipname = '/project/target/compress_complete.zip' (pwd查看绝对路径替换)

startdir = source_dir # 要压缩的文件夹路径

file_news = zipname # 压缩后文件夹的名字

z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED) # 参数一:文件夹名

for dirpath, dirnames, filenames in os.walk(startdir):

fpath = dirpath.replace(startdir, '')

fpath = fpath and fpath + os.sep or ''

for filename in filenames:

z.write(os.path.join(dirpath, filename), fpath+filename)

print ('压缩成功')

z.close()

复制代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值