python标准库之zipfile

python标准库zipfile

什么是zip文件?为何在网络上zip打包的文件比较常见?而不是rar?

zip是一种压缩归档的文件,zip开源的。

python的zipfile模块,有两个主要的类

ZipFile()

函数,判断是否为zip类型文件

zipfile. is_zipfile ( filename )

Returns True if filename is a valid ZIP file based on its magic number,otherwise returns False. filename may be a file or file-like object too


直接从压缩文件中读取文件内容
ZipFile. read ( name [, pwd ] )
# 实际上调用了self.open().read()

Return the bytes of the file name in the archive. name is the name of thefile in the archive


ZipFile. open ( name [, mode [, pwd ] ] )

Extract a member from the archive as a file-like object (ZipExtFile)


ZipFile. close ( )

Close the archive file. You must call close() before exiting your programor essential records will not be written.

ZipInfo()


# 压缩到指定文件
def file_zip(src, dst):
    zip_obj = ZipFile(dst, mode='w')
    zip_obj.write(src)
    zip_obj.close()


 # 解压缩
def unzip(src):
    zip_obj = ZipFile(src, mode='r')
    for info in zip_obj.filelist:
        zip_obj.extract(member=info)
    zip_obj.close()


zipfile的命令行接口

Usage:
    zipfile.py -l zipfile.zip        # Show listing of a zipfile
    zipfile.py -t zipfile.zip        # Test if a zipfile is valid
    zipfile.py -e zipfile.zip target # Extract zipfile into target dir
    zipfile.py -c zipfile.zip src ... # Create zipfile from sources

-c Create

-e Extract(提取)

-l List


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值