【Python】 压缩文件处理 zipfile & tarfile
【zipfile】
虽然叫zipfile,但是除了zip之外,rar,war,jar这些压缩(或者打包)文件格式也都可以处理。
zipfile模块常用的一些操作和方法:
is_zipfile(filename) 测试filename的文件,看它是否是个有效的zipfile
ZipFile(filename[,mode[,compression[,allowZip64]]]) 构造zipfile文件对象。mode可选r,w,a代表不同的打开文件的方式。compression指出这个zipfile用什么压缩方法,默认是ZIP_STORED,另一种选择是ZIP_DEFLATED。allowZip64是个bool型变量,当设置为True的时候就是说可以用来创建大小大于2G的zip文件,默认值是True
ZipInfo 包含一个zip文件中的子文件的信息,字段包括filename(包括相对zip包的路径),date_time(一个时间元组,该子文件最后修改时间),compress_type(该子文件的压缩格式)等等。
对于ZipFile实例z,有以下方法:
z.close() 关闭文件
z.extract(name[,path[,pwd]]) 从zip中提取一个文件,将它放到指定的path下,pwd是密码,用于被加密的zip文件
z.extractall(path[,pwd]) 将所有文件按照namelist中显示得那样的目录结构从当前zip中提取出来并放到path下。//这两个extract的path若不存在都会自动创建出来的,且这个path必须是个目录,解压时一定是把一个文件,包含其相对zip包路径的所有目录一起解压出来。总之有点坑,自己测试一下就知道了
z.namelist() 返回一个列表,内容是zip文件中所有子文件的path(相对于zip文件包而言的)。相当于是一个保存了zip内部目录结构的列表
z.infolist() 返回一个列表,内容是每个zip文件中子文件的ZipInfo对象,这个对象有上文中提到的那些字段
z.printdir() 将zip文件的目录结构打印到stdout上,包括每个文件的path,修改时间和大小
z.open(name[,mode[,pwd]]) 获取一个子文件的文件对象,可以将其用来read,readline,write等等操作
z.setpassword(psw) 可以为zip文件设置默认密码
z.testzip() 读取zip中的所有文件,验证他们的CRC校验和。返回第一个损坏文件的名称,如果所有文件都是完整的就返回None
z.write(filename[,arcname[,compression_type]]) 将zip外的文件filename写入到名为arcname的子文件中(当然arcname也是带有相对zip包的路径的),compression_type指定了压缩格式,也是ZIP_STORED或ZIP_DEFLATED。z的打开方式一定要是w或者a才能顺利写入文件。
贴上两个已经写好的常用的解压缩和压缩函数:
压缩一个目录:
def zip_dir(dirname,zipfilename):
filelist = []
if os.path.isfile(dirname):
filelist.append(dirname)
else :
for root, dirs, files in os.walk(dirname):
for dir in dirs:
filelist.append(os.path.join(root,dir))
for name in files:
filelist.append(os.path.join(root, name)) zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
for tar in filelist:
arcname = tar[len(dirname):]
#print arcname
zf.write(tar,arcname)
zf.close()
解压缩一个文件:(转自http://blog.csdn.net/linda1000/article/details/10432133)
def unzip_dir(zipfilename, unzipdirname):
fullzipfilename = os.path.abspath(zipfilename)
fullunzipdirname = os.path.abspath(unzipdirname)
print "Start to unzip file %s to folder %s ..." % (zipfilename, unzipdirname)
#Check input ...
if not os.path.exists(fullzipfilename):
print "Dir/File %s is not exist, Press any key to quit..." % fullzipfilename
inputStr = raw_input()
return
if not os.path.exists(fullunzipdirname):
os.mkdir(fullunzipdirname)
else:
if os.path.isfile(fullunzipdirname):
print "File %s is exist, are you sure to delet it first ? [Y/N]" % fullunzipdirname
while 1:
inputStr = raw_input()
if inputStr == "N" or inputStr == "n":
return
else:
if inputStr == "Y" or inputStr == "y":
os.remove(fullunzipdirname)
print "Continue to unzip files ..."
break #Start extract files ...
srcZip = zipfile.ZipFile(fullzipfilename, "r")
for eachfile in srcZip.namelist():
if eachfile.endswith('/'):
# is a directory
print 'Unzip directory %s ...' % eachfilename
os.makedirs(os.path.normpath(os.path.join(fullunzipdirname, eachfile)))
continue
print "Unzip file %s ..." % eachfile
eachfilename = os.path.normpath(os.path.join(fullunzipdirname, eachfile))
eachdirname = os.path.dirname(eachfilename)
if not os.path.exists(eachdirname):
os.makedirs(eachdirname)
fd=open(eachfilename, "wb")
fd.write(srcZip.read(eachfile))
fd.close()
srcZip.close()
print "Unzip file succeed!"
【tarfile】
linux上常用的tar文件不被zipfile支持,应该要用tarfile模块来处理tar文件,无论tar文件是否被压缩还是仅仅被打包,都可以读取和写入tar文件。和zipfile模块类似的,tarfile有以下一些方法和类:
is_tarfile(filename) 检查是否是个有效的tar文件
open([name[,mode]]) 和zipfile的ZipFile有所不同的是,这里的open除了指出打开文件的方式以外还指出了文件的压缩方式。通过filemode[:compression]的方式可以指出很多种文件模式:
'r' 读打开,如果文件是压缩得会被透明(???)地解压缩。这是默认打开方式
'r:' 读打开,不压缩文件
'r:gz' 读打开,使用gzip压缩文件
'r:bz2' 读打开,使用bzip2压缩文件
'a','a:' 追加打开,不压缩文件 //注意,a模式下不能加压缩格式的。如果想要给压缩包添加什么东西的话最好另寻他路
'w','w:' 写打开,不压缩文件
'w:gz' 写打开,使用gzip压缩文件
'w:bz2' 写打开只用bzip2压缩文件
TarInfo类对象 和ZipInfo类似的,一个子文件的TarInfo对象存储了这个子文件的一些信息。TarInfo对象有一些方法和属性:
it.gid/gname 获取这个子文件的组ID和组名称
it.uid/uname 获取这个子文件的用户id和用户名称
ti.isdir() 判断这个子文件是否是个目录
ti.isfile() 判断是否是个普通文件
ti.name 文件名
ti.mode 权限
ti.size 大小
ti.mtime 最后修改时间
由open返回的一个tarfile实例t有以下方法:
t.add(name[,arcname,[recursive]]) 将tar包外的文件或目录name添加到tar包内的arcname,当name是个目录时可把recursive设置为True来递归地加入tar包
t.close()
t.errorlevel 可以设置提取tar包中文件时如何确定处理错误,当这一属性为0时,错误将被忽略,为1时错误将导致IOError和OSError,如果设置为2非致命性错误将会导致TarError
t.extract(member[,path]) 从tar包中提取一个子文件,保存到指定目录下
t.extractfile(member) 从tar包中提取一个子文件,但返回的是个类文件对象,可以通过read,write等方法来操作文件的内容
t.getnames() 类似于zipfile中的namelist()
t.ignore_zeros 若这一个属性被设置为True的话,读取tar包时会跳过空块,如果这已设置为False则空块表示tar包的结束。这个属性的设置有利于读取损坏的tar包
t.list() 类似于zipfile的printdir(),但是其列出的信息更加详细,如果不要这么详细的信息,可以加上参数False
t.getmemebers() 返回一个列表,内容是所有文件的TarInfo对象
【Python】 压缩文件处理 zipfile & tarfile的更多相关文章
- Python的压缩文件处理 zipfile & tarfile
本文从以下两个方面, 阐述Python的压缩文件处理方式: 一. zipfile 二. tarfile 一. zipfile 虽然叫zipfile,但是除了zip之外,rar,war,jar这些压缩( ...
- 【Python】使用Python压缩文件/文件夹
[Python压缩文件夹]导入“zipfile”模块 def zip_ya(startdir,file_news): startdir = ".\\123" #要压缩的文件夹路径 ...
- Python压缩文件/文件夹
[Python压缩文件夹]导入“zipfile”模块 def zip_ya(startdir,file_news): startdir = ".\\123" #要压缩的文件夹路径 ...
- python 压缩模块大杂烩(zipfile,bz2,lzma,gzip,tarfile,zlib)
[*] 以下压缩模块请结合python的官方文档(https://docs.python.org/3.5/library/index.html)来实践或者对比(我的是python 3.5) 1.pyt ...
- Python脚本破解压缩文件口令(zipfile)
环境:Windows python版本2.7.15 Python中操作zip压缩文件的模块是 zipfile . 相关文章:Python中zipfile压缩文件模块的使用 我们破解压缩文件的口令也是用 ...
- python压缩文件
#coding=utf-8 #压缩文件 import os,os.path import zipfile #压缩:传路径,文件名 def zip_compression(dirname,zipfile ...
- python 压缩文件为zip后删除原文件
压缩.log 文件为zip后删除原文件 需要注意:本人作为小白,该脚本需要和.log在一起,后面有时间需要改正. #!/usr/local/python/bin/python #-*-coding=u ...
- python 压缩文件(解决压缩路径问题)
#压缩文件 def Zip_files(): datapath = filepath # 证据路径 file_newname = datapath + '.zip' # 压缩文件的名字 log.deb ...
- Python压缩文件夹 tar.gz .zip
打包压缩生成 XXX.tar.gz 文件 import os import tarfile if os.path.exists(outputFileName): with tarfile.open(o ...
随机推荐
- vscode格式化Vue出现的问题
一.VSCode中使用vetur插件格式化vue文件时,js代码会自动加上冒号和分号 本来就是简写比较方便舒服,结果一个格式化回到解放前 最后找到问题原因: 首先,vetur默认设置是这个样的.也就是 ...
- AndFix
AndFix 是阿里巴巴开源的 Android 应用热修复工具,帮助 Anroid 开发者修复应用的线上问题.Andfix 是 "Android hot-fix" 的缩写.支持 A ...
- REALTEK 刷机方法 法
REALTEK 是通用板最多的IC 方案之一,什么常说的2025 2270 2023 2033 2525 2545 2660 2280 2662 2670 2672 2674 2661 2668 ...
- 笔记︱风控分类模型种类(决策、排序)比较与模型评估体系(ROC/gini/KS/lift)
每每以为攀得众山小,可.每每又切实来到起点,大牛们,缓缓脚步来俺笔记葩分享一下吧,please~ --------------------------- 本笔记源于CDA-DSC课程,由常国珍老师主讲 ...
- “net usershare”返回错误 255
1 错误描述 youhaidong@youhaidong:~$ sudo nautilus (nautilus:4429): Gtk-WARNING **: Failed to register cl ...
- 异常-----freemarker.core.NonStringException
一,案例一 1.1.错误描述 <html> <head> <meta http-equiv="content-type" content=" ...
- java SpringWeb 接收安卓android传来的图片集合及其他信息入库存储
公司是做APP的,进公司一年了还是第一次做安卓的接口 安卓是使用OkGo.post("").addFileParams("key",File); 通过这种方式传 ...
- C# 高效字符串连接 StringBuilder介绍
在介绍StringBuilder之前,必须要先了解string的特性. string在.NET中属于基本数据类型,也是基本数据类型中唯一的引用类型.字符串可以声明为常量,但它却放在了堆中. 一:不可改 ...
- 【转载】 Spark性能优化:资源调优篇
在开发完Spark作业之后,就该为作业配置合适的资源了.Spark的资源参数,基本都可以在spark-submit命令中作为参数设置.很多Spark初学者,通常不知道该设置哪些必要的参数,以及如何设置 ...
- RobotFramework自动化测试框架的基础关键字(一)
1.1.1 如何搜索RobotFramework的关键字 有两种方式可以快速的打开RIDE的关键字搜索对话框 1.选择菜单栏Tools->Search Keywords,然后会出现 ...