::-- ZoomQuiet [DateTime(2008-02-16T04:46:26Z)] TableOfContents

Include(CPUGnav)

1. deflate算法压缩

2008/2/16 马踏飞燕 <[email protected]>: > 现在需要将一段内容用deflate算法压缩一下,但是找了半天也没找到python有这方面的代码阿。 > 我用zlib压缩出来的结果与用C#压缩出来的结果不一致,导致对方应用程序读不出来,胸闷阿。。。 > 有没有相关的代码阿? >

   1 #   Programmer: limodou
   2 #   E-mail:     [email protected]
   3 #
   4 #   Copyleft 2005 limodou
   5 #
   6 #   Distributed under the terms of the GPL (GNU Public License)
   7 #
   8 #   ZFile is free software; you can redistribute it and/or modify
   9 #   it under the terms of the GNU General Public License as published by
  10 #   the Free Software Foundation; either version 2 of the License, or
  11 #   (at your option) any later version.
  12 #
  13 #   This program is distributed in the hope that it will be useful,
  14 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
  15 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16 #   GNU General Public License for more details.
  17 #
  18 #   You should have received a copy of the GNU General Public License
  19 #   along with this program; if not, write to the Free Software
  20 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  21 #
  22 #   $Id$
  23 
  24 import zipfile
  25 import os
  26 import os.path
  27 import sys
  28 import getopt
  29 
  30 __appname__ = 'zfile'
  31 __author__ = 'limodou'
  32 __version__ = '0.1'
  33 
  34 class ZFile(object):
  35    def __init__(self, filename, mode='r', basedir='', visitor=None):
  36        self.filename = filename
  37        self.mode = mode
  38        if self.mode in ('w', 'a'):
  39            self.zfile = zipfile.ZipFile(filename, self.mode,
  40 compression=zipfile.ZIP_DEFLATED)
  41        else:
  42            self.zfile = zipfile.ZipFile(filename, self.mode)
  43        self.basedir = basedir
  44        if not self.basedir:
  45            self.basedir = os.path.dirname(filename)
  46        self.basedir =
  47 os.path.normpath(os.path.abspath(self.basedir)).replace('\\', '/')
  48        self.visitor = visitor
  49 
  50    def addfile(self, path, arcname=None):
  51        path = os.path.normpath(path).replace('\\', '/')
  52        if not arcname:
  53            if path.startswith(self.basedir + '/'):
  54                arcname = path[len(self.basedir) + 1:]
  55            else:
  56                arcname = ''
  57        if self.visitor:
  58            self.visitor(path, arcname)
  59        self.zfile.write(path, arcname)
  60 
  61    def addstring(self, arcname, string):
  62        self.zfile.writestr(arcname, string)
  63 
  64    def addfiles(self, paths):
  65        for path in paths:
  66            if isinstance(path, tuple):
  67                p, arcname = path
  68                p = os.path.abspath(p)
  69                if os.path.isdir(p):
  70                    self.addpath(p)
  71                else:
  72                    self.addfile(p, arcname)
  73            else:
  74                path = os.path.abspath(path)
  75                if os.path.isdir(path):
  76                    self.addpath(path)
  77                else:
  78                    self.addfile(path)
  79 
  80    def addpath(self, path):
  81        files = self._getallfiles(path)
  82        self.addfiles(files)
  83 
  84    def close(self):
  85        self.zfile.close()
  86 
  87    def extract_to(self, path):
  88        for p in self.zfile.namelist():
  89            self.extract(p, path)
  90 
  91    def extract(self, filename, path):
  92        if not filename.endswith('/'):
  93            f = os.path.join(path, filename)
  94            dir = os.path.dirname(f)
  95            if not os.path.exists(dir):
  96                os.makedirs(dir)
  97            file(f, 'wb').write(self.zfile.read(filename))
  98 
  99    def _getallfiles(self, path):
 100        fset = []
 101        for root, dirs, files in os.walk(path):
 102            for f in files:
 103                fset.append(os.path.join(root, f))
 104        return fset
 105 
 106 
 107 def create(zfile, files, basedir='', visitor=None):
 108    z = ZFile(zfile, 'w', basedir, visitor=visitor)
 109    z.addfiles(files)
 110    z.close()
 111 
 112 def extract(zfile, path):
 113    z = ZFile(zfile)
 114    z.extract_to(path)
 115    z.close()
 116 
 117 def main():
 118    #process command line
 119 
 120    cmdstring = "Vhl:i:b:"
 121 
 122    try:
 123        opts, args = getopt.getopt(sys.argv[1:], cmdstring, [])
 124    except getopt.GetoptError:
 125        Usage()
 126        sys.exit(1)
 127 
 128    filelist = ''
 129    inputfiles = ''
 130    basedir = ''
 131    for o, a in opts:
 132        if o == '-V':       #version
 133            Version()
 134            sys.exit()
 135        elif o == '-h':
 136            Usage()
 137            sys.exit()
 138        elif o == '-l':
 139            filelist = a
 140        elif o == '-i':
 141            inputfiles = a
 142        elif o == '-b':
 143            basedir = a
 144 
 145    if not basedir:
 146        basedir = os.getcwd()
 147 
 148    if inputfiles and filelist or len(args) < 1:
 149        Usage()
 150        sys.exit()
 151 
 152    zipfile = args[0]
 153    if not inputfiles and len(args) > 1:
 154        fout = None
 155        if filelist:
 156            fout = file(filelist, 'w')
 157 
 158        def visitor(path, arcname, f=fout):
 159            if f:
 160                f.write(arcname + '\n')
 161 
 162        if len(args) == 2 and os.path.isdir(args[1]):
 163            create(zipfile, args[1:], basedir, visitor)
 164        else:
 165            create(zipfile, args[1:], basedir, visitor=visitor)
 166        if fout:
 167            fout.close()
 168    elif inputfiles and len(args) == 1:
 169        lines = file(inputfiles).readlines()
 170        files = [f.strip() for f in lines]
 171        create(zipfile, files, basedir)
 172 
 173    else:
 174        Usage()
 175        sys.exit()
 176 
 177 
 178 def Usage():
 179    print """Usage %s [options] zipfilename directories|filenames
 180      %s -i listfile zipfilename
 181 
 182 -V      Show version
 183 -h      Show usage
 184 -l      Create a listinfo file
 185 -i      Input file list
 186 -b      Specify base directory
 187 """ % (sys.argv[0], sys.argv[0])
 188 
 189 def Version():
 190    print """%s Copyleft GPL
 191 Author: %s
 192 Version: %s""" % (__appname__, __author__, __version__)
 193 
 194 if __name__ == '__main__':
 195 #    a = ZFile('d:/aaaa.zip', 'w')
 196 #    a.addfile('d:/a.csv')
 197 #    a.addfile('d:/test/a.JPG')
 198 #    a.addfile('d:/test/mixin/main.py', 'main.py')
 199 #    files = ['d:/a.csv', 'd:/test/a.JPG', ('d:/test/mixin/main.py', 'main.py')]
 200 ##    a.addfiles(files)
 201 ##    a.close()
 202 #    create('d:/aaaa.zip', files)
 203 #    a = ZFile('d:/aaaa.zip')
 204 #    a.extract_to('d:/test/aaaa')
 205 #    extract('d:/aaaa.zip', 'd:/test/aaaa/aaaa')
 206    main()

1.1. 反馈

PageComment2 [:/PageCommentData:PageCommentData]