zipfile的压缩和解压缩

本文详细介绍了Python中ZipFile模块的使用方法,包括压缩和解压缩功能。解释了不同压缩模式的区别,如ZIP_STORED和ZIP_DEFLATED,并提供了代码示例。此外,还讲解了解压缩的具体操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

zipfile是python提供的内置的压缩方法

可以对zip文件进行压缩和解压缩

压缩:

 zf = ZipFile("out.zip", "w", mode=zipfile.ZIP_STORED)

zf.write("文件全路径", "归档文件全路径(也就是写入压缩包的相对路径)")

说明:

zipfile.ZIP_STORED是默认压缩方式,其实只是存储,并不进行内容压缩

如果要使用压缩,必须要import zlib库才可以

如下:

import zipfile
try:
    import zlib
    mode= zipfile.ZIP_DEFLATED
except:
    mode= zipfile.ZIP_STORED

zip= zipfile.ZipFile('zipfilename', 'w', mode)
zip.write(item)
zip.close()

再来查看官方文档:

zipfile. ZIP_STORED

The numeric constant for an uncompressed archive member.

zipfile. ZIP_DEFLATED

The numeric constant for the usual ZIP compression method. This requires the zlib module. No other compression methods are currently supported.

难怪我压缩发现文件越来越大了

但是zipfile用的默认压缩算法是zlib,目前仅支持这个。


解压缩:

解压缩就比较简单了

ZipFile. extract ( member [, path [, pwd ] ] )

Extract a member from the archive to the current working directory; member must be its full name or a ZipInfo object). Its file information is extracted as accurately as possible. path specifies a different directory to extract to. member can be a filename or a ZipInfo object. pwd is the password used for encrypted files.

Returns the normalized path created (a directory or new file).

New in version 2.6.

Note

If a member filename is an absolute path, a drive/UNC sharepoint and leading (back)slashes will be stripped, e.g.: ///foo/bar becomes foo/bar on Unix, and C:\foo\bar becomes foo\bar on Windows. And all ".." components in a member filename will be removed, e.g.: ../../foo../../ba..r becomes foo../ba..r. On Windows illegal characters (:, <, >, |, ", ?, and *) replaced by underscore (_).

ZipFile. extractall ( [ path [, members [, pwd ] ] ] )

Extract all members from the archive to the current working directory. path specifies a different directory to extract to. members is optional and must be a subset of the list returned by namelist(). pwd is the password used for encrypted files.


说明了读文档的能力还是不够细!要加强!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值