【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的更多相关文章

  1. Python的压缩文件处理 zipfile & tarfile

    本文从以下两个方面, 阐述Python的压缩文件处理方式: 一. zipfile 二. tarfile 一. zipfile 虽然叫zipfile,但是除了zip之外,rar,war,jar这些压缩( ...

  2. 【Python】使用Python压缩文件/文件夹

    [Python压缩文件夹]导入“zipfile”模块 def zip_ya(startdir,file_news): startdir = ".\\123" #要压缩的文件夹路径 ...

  3. Python压缩文件/文件夹

    [Python压缩文件夹]导入“zipfile”模块 def zip_ya(startdir,file_news): startdir = ".\\123" #要压缩的文件夹路径 ...

  4. python 压缩模块大杂烩(zipfile,bz2,lzma,gzip,tarfile,zlib)

    [*] 以下压缩模块请结合python的官方文档(https://docs.python.org/3.5/library/index.html)来实践或者对比(我的是python 3.5) 1.pyt ...

  5. Python脚本破解压缩文件口令(zipfile)

    环境:Windows python版本2.7.15 Python中操作zip压缩文件的模块是 zipfile . 相关文章:Python中zipfile压缩文件模块的使用 我们破解压缩文件的口令也是用 ...

  6. python压缩文件

    #coding=utf-8 #压缩文件 import os,os.path import zipfile #压缩:传路径,文件名 def zip_compression(dirname,zipfile ...

  7. python 压缩文件为zip后删除原文件

    压缩.log 文件为zip后删除原文件 需要注意:本人作为小白,该脚本需要和.log在一起,后面有时间需要改正. #!/usr/local/python/bin/python #-*-coding=u ...

  8. python 压缩文件(解决压缩路径问题)

    #压缩文件 def Zip_files(): datapath = filepath # 证据路径 file_newname = datapath + '.zip' # 压缩文件的名字 log.deb ...

  9. Python压缩文件夹 tar.gz .zip

    打包压缩生成 XXX.tar.gz 文件 import os import tarfile if os.path.exists(outputFileName): with tarfile.open(o ...

随机推荐

  1. python︱函数、for、_name_杂记

    新手入门python,开始写一些简单函数,慢慢来,加油~ 一.函数 def myadd(a=1,b=100): result = 0 i = a while i <= b: # 默认值为1+2+ ...

  2. Linux 系统裁剪笔记 4 (内核配置选项及删改)

     CDROM filesystem support(CONFIG_ISO9660_FS)[Y/m/n/?]有标准光驱的系统应该选Y.Minix fs support(CONFIG_MINIX_FS)[ ...

  3. 利用apache自带的工具 分割访问日志

    httpd.conf中CustomLog logs/access.log common 改成 CustomLog "|c:/apache/bin/rotatelogs.exe c:/apac ...

  4. Windows PE入门基础知识:Windows PE的作用、命名规则、启动方式、启动原理

    Windows PE的全名是WindowsPreinstallationEnvironment(WinPE)直接从字面上翻译就 是"Windows预安装环境".微软的本意是:Win ...

  5. freemarker自定义标签报错(四)

    freemarker自定义标签 1.错误描述 六月 05, 2014 11:31:35 下午 freemarker.log.JDK14LoggerFactory$JDK14Logger error 严 ...

  6. ASP.NET性能调试

    该文转自mx5721的博客:http://blog.csdn.net/mx5721/article/details/9138135 设计考虑 性能和安全的考虑 应用程序逻辑划分的考虑:逻辑分层,然后使 ...

  7. C++遍历二维数组的四种方法

    #include <iostream> using std::cin; using std::cout; using std::endl; using std::string; using ...

  8. Python基础_文件的的处理及异常处理

    今天主要讲讲文件读写及异常处理. 一.文件操作 1.1 文件的创建及读 打开文件 open 函数  open(file,[option]) file 是要打开的文件 option是可选择的参数文件的打 ...

  9. Linux性能分析工具top命令详解

    top命令是Linux下常用的性能分析工具,能够实时显示系统中各个进程的资源占用状况,常用于服务端性能分析. top命令说明 [www.linuxidc.com@linuxidc-t-tomcat-1 ...

  10. Docker学习——Lepus部署

    Lepus部署(基于docker)及mysql慢查询配置 介绍 Lepus是一个由Python+PHP开发的数据库企业级监控系统,可用于MySQL/Oracle/MongoDB/Redis 下载镜像 ...