python zip压缩_Python zip压缩与解压(zipfile模块实例)

python中提供了文件压缩的zipfile模块。

zipfile模块() 用于压缩文件成zip及解压zip文件,模块介绍如下。

zipfile.ZipFile(file, mode) open a ZIP file,where file can be either a path to a file or a file-like object. mode can be read “r” , write “w”, or append “a”以某种模式打开ZIP 文档。

默认值为’r’ 表示读已经存在的zip文件,‘w’ 表示新建一个zip文档或覆盖一个存在的同名zip文档, ‘a’ 表示将数据附加到一个现存的zip文档中。

在 class zipfile.ZipFile中有如下模块:

ZipFile.namelist() return a list of archive members by name. 返回一个列表包含zipfile里面的文件

ZipFile.close() close the archive file。当解压完zip文件以后关闭zipfile.

ZipFile.extractall(self, path=None, members=None, pwd=None) Extract all members from the archive to the current working directory. Path specified a different directory to extract to. Member is optional and must be subset of the list returned by namelist().

解压全部文件到当前路径,也可以加压到指定路径。

ZipFile.extract(self, member, path=None, pwd=None) extract a member from the archive to the current working directory, member must be its full name. 从ZIP文件里解压一个文件到当前路径,该文件必须以全名给定。

ZipFile.setpassword(pwd) set pwd as default password to extract encrypted files. 设置一个默认密码用于解压文件。

ZipFile.write(filename) write the file named filename to the archive. 将文件写入zip文档。

例1,压缩文件成zip包 代码示例:

import zipfile

import sys

import os

filepath = sys.argv[1]

outputpath = sys.argv[2]

os.chdir(filepath)

filelist = os.listdir(filepath) # list the files need to achieve

zipfilename = filepath.split("/")[-1] #fetch the last name of path as zipfile name

ZipFileobj = zipfile.ZipFile(filepath+"/"+ zipfilename +".zip", 'w') #create a zip file

for files in filelist:# use “for” to add files into zip file

ZipFileobj.write(files)

ZipFileobj.close()

print "zipfile already created!"

例2,解压zip包 代码示例:

import zipfile

import sys

zipfilepath = sys.argv[1]

outputpath = sys.argv[2]

print zipfilepath

zipfiles = zipfile.ZipFile(zipfilepath, "r")

zipfiles.extractall(outputpath)

zipfiles.close()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值