Python----压缩与解压缩文件

来源:互联网 发布:奥登体测数据 编辑:程序博客网 时间:2024/05/15 07:18

Python压缩与解压缩文件

 

Python能够直接处理zip文件中的数据,例如需要将对应目录或多文件打包或压缩成zip格式,或者需要查看一个zip格式的归档文件中部分或所有的文件同时避免将这些文件展开到磁盘上,自1.6版本起,python中zipfile模块以实现相应操作。不过zipfile模块目前还不能处理分卷zip文件和带有注释的zip文件。

目前仅整理对zip文件的读取与写入的两种基本操作。

一、读取zip文件

首先,通过zipfile模块打开指定zip文件,如:

zpfd = zipfile.ZipFile(path, mode='r')

对于zipfile,其标志与open所用的打开文件标志有所不同,不能识别 'rb'。

然后,读取zip文件中的内容,zipfile对象提供一个read(name)的方法,name为zip文件中的一个文件入口,执行完成之后,将返回读出的内容,如:

for filename in zpfd.namelist():

    tmpcont = zpfd.read(filename)

    print 'len(tmpcont)', 'tmpcont'

需要注意的是,读取zip文件时,只能读取内容

二、写入zip文件

首先,需要zipfile模块写打开或创建zip文件,如:

zpfd = zipfile.ZipFile(path, mode='w')

写打开是标志可以为'w'或'a'('a'表示写入一个zip文件), 或者传入第三个参数cmopression压缩标志

compression=zipfile.ZIP_DEFLATED 需要导入zlib模块

compression=zipfile.ZIP_STORED则表示只对文件进行打包,并不压缩

写入有两种方式,一种是直接写入一个已经存在的文件,可使用zipfile对象中write(filename, arcname, compress_type)第一个参数为文件名,第二个参数指写入zip文件中的文件名,默认与filename一致,第三个参数压缩标志可以覆盖打开zipfile时的使用参数;另一种是写入一个字符串,可使用zipfile对象中的writestr(zinfo_or_arcname, bytes),第一个参数是zipinfo对象或写到zip文件中的压缩名,第二个参数是待写入的字符串

最后,对于打开的zipfile对象需要进行关闭,从而使得写入内容真正写入磁盘,即:

zpfd.close()

以下是一个实现简单压缩与解压缩的实例

[python] view plain copy
 print?
  1. import os,sys  
  2. import zipfile  
  3.   
  4. def zip_dir(dirname, zipfilename):  
  5.     filelist = []  
  6.     #Check input ...  
  7.     fulldirname = os.path.abspath(dirname)  
  8.     fullzipfilename = os.path.abspath(zipfilename)  
  9.     print "Start to zip %s to %s ..." % (fulldirname, fullzipfilename)  
  10.     if not os.path.exists(fulldirname):  
  11.         print "Dir/File %s is not exist, Press any key to quit..." % fulldirname  
  12.         inputStr = raw_input()  
  13.         return  
  14.     if os.path.isdir(fullzipfilename):  
  15.         tmpbasename = os.path.basename(dirname)  
  16.         fullzipfilename = os.path.normpath(os.path.join(fullzipfilename, tmpbasename))  
  17.     if os.path.exists(fullzipfilename):      
  18.         print "%s has already exist, are you sure to modify it ? [Y/N]" % fullzipfilename  
  19.         while 1:  
  20.             inputStr = raw_input()  
  21.             if inputStr == "N" or inputStr == "n" :  
  22.                 return  
  23.             else:  
  24.                 if inputStr == "Y" or inputStr == "y" :  
  25.                     print "Continue to zip files..."  
  26.                     break  
  27.   
  28.     #Get file(s) to zip ...  
  29.     if os.path.isfile(dirname):  
  30.         filelist.append(dirname)  
  31.         dirname = os.path.dirname(dirname)  
  32.     else:  
  33.         #get all file in directory  
  34.         for root, dirlist, files in os.walk(dirname):  
  35.             for filename in files:  
  36.                 filelist.append(os.path.join(root,filename))  
  37.   
  38.     #Start to zip file ...  
  39.     destZip = zipfile.ZipFile(fullzipfilename, "w")  
  40.     for eachfile in filelist:  
  41.         destfile = eachfile[len(dirname):]  
  42.         print "Zip file %s..." % destfile  
  43.         destZip.write(eachfile, destfile)  
  44.     destZip.close()  
  45.     print "Zip folder succeed!"  
  46.       
  47. def unzip_dir(zipfilename, unzipdirname):  
  48.     fullzipfilename = os.path.abspath(zipfilename)  
  49.     fullunzipdirname = os.path.abspath(unzipdirname)  
  50.     print "Start to unzip file %s to folder %s ..." % (zipfilename, unzipdirname)  
  51.     #Check input ...  
  52.     if not os.path.exists(fullzipfilename):  
  53.         print "Dir/File %s is not exist, Press any key to quit..." % fullzipfilename  
  54.         inputStr = raw_input()  
  55.         return  
  56.     if not os.path.exists(fullunzipdirname):  
  57.         os.mkdir(fullunzipdirname)  
  58.     else:  
  59.         if os.path.isfile(fullunzipdirname):  
  60.             print "File %s is exist, are you sure to delet it first ? [Y/N]" % fullunzipdirname  
  61.             while 1:  
  62.                 inputStr = raw_input()  
  63.                 if inputStr == "N" or inputStr == "n":  
  64.                     return  
  65.                 else:  
  66.                     if inputStr == "Y" or inuptStr == "y":  
  67.                         os.remove(fullunzipdirname)  
  68.                         print "Continue to unzip files ..."  
  69.                         break  
  70.               
  71.     #Start extract files ...  
  72.     srcZip = zipfile.ZipFile(fullzipfilename, "r")  
  73.     for eachfile in srcZip.namelist():  
  74.         print "Unzip file %s ..." % eachfile  
  75.         eachfilename = os.path.normpath(os.path.join(fullunzipdirname, eachfile))  
  76.         eachdirname = os.path.dirname(eachfilename)  
  77.         if not os.path.exists(eachdirname):  
  78.             os.makedirs(eachdirname)  
  79.         fd=open(eachfilename, "wb")  
  80.         fd.write(srcZip.read(eachfile))  
  81.         fd.close()  
  82.     srcZip.close()  
  83.     print "Unzip file succeed!"  
  84.   
  85.   
  86.   
  87. def print_help(toolname):  
  88.     print """ 
  89.     This program can zip given folder to destination file, or unzip given zipped file to destination folder. 
  90.     Usage: %s [option] [arg]... 
  91.     -h: print this help message and exit (also --help) 
  92.     -u unzip: unzip given zipped file to destination folder, 
  93.         usage: %s -u/-unzip zipfilename, unzipdirname 
  94.     -z zip: zip given folder to destination file 
  95.         usage: %s -z/zip dirname, zipfilename 
  96.     """  % (toolname, toolname, toolname)  
  97.   
  98. if __name__ == '__main__':  
  99.     if len(sys.argv) < 2:  
  100.         print_help(sys.argv[0])  
  101.         sys.exit()  
  102.     if sys.argv[1].startswith('--'):  
  103.         option = sys.argv[1][2:]  
  104.         if option == 'version':  
  105.             print 'Get no version information'  
  106.         else:  
  107.             if option != 'help':  
  108.                 print "Unknown option"  
  109.             print_help(sys.argv[0])  
  110.         sys.exit()  
  111.     if sys.argv[1].startswith('-'):  
  112.         if len(sys.argv) < 4 :  
  113.             print_help(sys.argv[0])  
  114.             sys.exit()  
  115.         option = sys.argv[1][1:]  
  116.         if option == 'u' or option == 'unzip':  
  117.             zipfilepath = sys.argv[2]  
  118.             unzipdirpath = sys.argv[3]  
  119.             unzip_dir(zipfilepath, unzipdirpath)  
  120.         else:  
  121.             if option == 'z' or option == 'zip':  
  122.                 dirpath = sys.argv[2]  
  123.                 zipfilepath = sys.argv[3]  
  124.                 zip_dir(dirpath, zipfilepath)  
  125.             else:  
  126.                 print_help(sys.argv[0])  
  127.                 sys.exit()  
0 0