::-- ZoomQuiet [2008-02-16 04:46:26]
Contents
1. deflate算法压缩
2008/2/16 马踏飞燕 <honeyday.mj@gmail.com>:
- 现在需要将一段内容用deflate算法压缩一下,但是找了半天也没找到python有这方面的代码阿。
- 我用zlib压缩出来的结果与用C#压缩出来的结果不一致,导致对方应用程序读不出来,胸闷阿。。。
- 有没有相关的代码阿?
1.1. limodou
{{{limodou <limodou@gmail.com> reply-to python-cn@googlegroups.com, to python-cn@googlegroups.com, date Sat, Feb 16, 2008 at 10:36 AM }}} subject [CPyUG:40252] Re: python如何使用deflate压缩算法?
Toggle line numbers
1 # Programmer: limodou
2 # E-mail: limodou@gmail.com
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,compression=zipfile.ZIP_DEFLATED)
40 else:
41 self.zfile = zipfile.ZipFile(filename, self.mode)
42 self.basedir = basedir
43 if not self.basedir:
44 self.basedir = os.path.dirname(filename)
45 self.basedir = os.path.normpath(os.path.abspath(self.basedir)).replace('\\', '/')
46 self.visitor = visitor
47
48 def addfile(self, path, arcname=None):
49 path = os.path.normpath(path).replace('\\', '/')
50 if not arcname:
51 if path.startswith(self.basedir + '/'):
52 arcname = path[len(self.basedir) + 1:]
53 else:
54 arcname = ''
55 if self.visitor:
56 self.visitor(path, arcname)
57 self.zfile.write(path, arcname)
58
59 def addstring(self, arcname, string):
60 self.zfile.writestr(arcname, string)
61
62 def addfiles(self, paths):
63 for path in paths:
64 if isinstance(path, tuple):
65 p, arcname = path
66 p = os.path.abspath(p)
67 if os.path.isdir(p):
68 self.addpath(p)
69 else:
70 self.addfile(p, arcname)
71 else:
72 path = os.path.abspath(path)
73 if os.path.isdir(path):
74 self.addpath(path)
75 else:
76 self.addfile(path)
77
78 def addpath(self, path):
79 files = self._getallfiles(path)
80 self.addfiles(files)
81
82 def close(self):
83 self.zfile.close()
84
85 def extract_to(self, path):
86 for p in self.zfile.namelist():
87 self.extract(p, path)
88
89 def extract(self, filename, path):
90 if not filename.endswith('/'):
91 f = os.path.join(path, filename)
92 dir = os.path.dirname(f)
93 if not os.path.exists(dir):
94 os.makedirs(dir)
95 file(f, 'wb').write(self.zfile.read(filename))
96
97 def _getallfiles(self, path):
98 fset = []
99 for root, dirs, files in os.walk(path):
100 for f in files:
101 fset.append(os.path.join(root, f))
102 return fset
103
104
105 def create(zfile, files, basedir='', visitor=None):
106 z = ZFile(zfile, 'w', basedir, visitor=visitor)
107 z.addfiles(files)
108 z.close()
109
110 def extract(zfile, path):
111 z = ZFile(zfile)
112 z.extract_to(path)
113 z.close()
114
115 def main():
116 #process command line
117
118 cmdstring = "Vhl:i:b:"
119
120 try:
121 opts, args = getopt.getopt(sys.argv[1:], cmdstring, [])
122 except getopt.GetoptError:
123 Usage()
124 sys.exit(1)
125
126 filelist = ''
127 inputfiles = ''
128 basedir = ''
129 for o, a in opts:
130 if o == '-V': #version
131 Version()
132 sys.exit()
133 elif o == '-h':
134 Usage()
135 sys.exit()
136 elif o == '-l':
137 filelist = a
138 elif o == '-i':
139 inputfiles = a
140 elif o == '-b':
141 basedir = a
142
143 if not basedir:
144 basedir = os.getcwd()
145
146 if inputfiles and filelist or len(args) < 1:
147 Usage()
148 sys.exit()
149
150 zipfile = args[0]
151 if not inputfiles and len(args) > 1:
152 fout = None
153 if filelist:
154 fout = file(filelist, 'w')
155
156 def visitor(path, arcname, f=fout):
157 if f:
158 f.write(arcname + '\n')
159
160 if len(args) == 2 and os.path.isdir(args[1]):
161 create(zipfile, args[1:], basedir, visitor)
162 else:
163 create(zipfile, args[1:], basedir, visitor=visitor)
164 if fout:
165 fout.close()
166 elif inputfiles and len(args) == 1:
167 lines = file(inputfiles).readlines()
168 files = [f.strip() for f in lines]
169 create(zipfile, files, basedir)
170
171 else:
172 Usage()
173 sys.exit()
174
175
176 def Usage():
177 print """Usage %s [options] zipfilename directories|filenames
178 %s -i listfile zipfilename
179
180 -V Show version
181 -h Show usage
182 -l Create a listinfo file
183 -i Input file list
184 -b Specify base directory
185 """ % (sys.argv[0], sys.argv[0])
186
187 def Version():
188 print """%s Copyleft GPL
189 Author: %s
190 Version: %s""" % (__appname__, __author__, __version__)
191
192 if __name__ == '__main__':
193 # a = ZFile('d:/aaaa.zip', 'w')
194 # a.addfile('d:/a.csv')
195 # a.addfile('d:/test/a.JPG')
196 # a.addfile('d:/test/mixin/main.py', 'main.py')
197 # files = ['d:/a.csv', 'd:/test/a.JPG', ('d:/test/mixin/main.py', 'main.py')]
198 ## a.addfiles(files)
199 ## a.close()
200 # create('d:/aaaa.zip', files)
201 # a = ZFile('d:/aaaa.zip')
202 # a.extract_to('d:/test/aaaa')
203 # extract('d:/aaaa.zip', 'd:/test/aaaa/aaaa')
204 main()