python如何使用deflate压缩算法?

5 views
Skip to first unread message

马踏飞燕

unread,
Feb 15, 2008, 1:32:53 PM2/15/08
to Python.cn@google
现在需要将一段内容用deflate算法压缩一下,但是找了半天也没找到python有这方面的代码阿。
我用zlib压缩出来的结果与用C#压缩出来的结果不一致,导致对方应用程序读不出来,胸闷阿。。。
有没有相关的代码阿?

limodou

unread,
Feb 15, 2008, 9:36:45 PM2/15/08
to pyth...@googlegroups.com
2008/2/16 马踏飞燕 <honey...@gmail.com>:

> 现在需要将一段内容用deflate算法压缩一下,但是找了半天也没找到python有这方面的代码阿。
> 我用zlib压缩出来的结果与用C#压缩出来的结果不一致,导致对方应用程序读不出来,胸闷阿。。。
> 有没有相关的代码阿?
>
# Programmer: limodou
# E-mail: lim...@gmail.com
#
# Copyleft 2005 limodou
#
# Distributed under the terms of the GPL (GNU Public License)
#
# ZFile is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id$

import zipfile
import os
import os.path
import sys
import getopt

__appname__ = 'zfile'
__author__ = 'limodou'
__version__ = '0.1'

class ZFile(object):
def __init__(self, filename, mode='r', basedir='', visitor=None):
self.filename = filename
self.mode = mode
if self.mode in ('w', 'a'):
self.zfile = zipfile.ZipFile(filename, self.mode,
compression=zipfile.ZIP_DEFLATED)
else:
self.zfile = zipfile.ZipFile(filename, self.mode)
self.basedir = basedir
if not self.basedir:
self.basedir = os.path.dirname(filename)
self.basedir =
os.path.normpath(os.path.abspath(self.basedir)).replace('\\', '/')
self.visitor = visitor

def addfile(self, path, arcname=None):
path = os.path.normpath(path).replace('\\', '/')
if not arcname:
if path.startswith(self.basedir + '/'):
arcname = path[len(self.basedir) + 1:]
else:
arcname = ''
if self.visitor:
self.visitor(path, arcname)
self.zfile.write(path, arcname)

def addstring(self, arcname, string):
self.zfile.writestr(arcname, string)

def addfiles(self, paths):
for path in paths:
if isinstance(path, tuple):
p, arcname = path
p = os.path.abspath(p)
if os.path.isdir(p):
self.addpath(p)
else:
self.addfile(p, arcname)
else:
path = os.path.abspath(path)
if os.path.isdir(path):
self.addpath(path)
else:
self.addfile(path)

def addpath(self, path):
files = self._getallfiles(path)
self.addfiles(files)

def close(self):
self.zfile.close()

def extract_to(self, path):
for p in self.zfile.namelist():
self.extract(p, path)

def extract(self, filename, path):
if not filename.endswith('/'):
f = os.path.join(path, filename)
dir = os.path.dirname(f)
if not os.path.exists(dir):
os.makedirs(dir)
file(f, 'wb').write(self.zfile.read(filename))

def _getallfiles(self, path):
fset = []
for root, dirs, files in os.walk(path):
for f in files:
fset.append(os.path.join(root, f))
return fset


def create(zfile, files, basedir='', visitor=None):
z = ZFile(zfile, 'w', basedir, visitor=visitor)
z.addfiles(files)
z.close()

def extract(zfile, path):
z = ZFile(zfile)
z.extract_to(path)
z.close()

def main():
#process command line

cmdstring = "Vhl:i:b:"

try:
opts, args = getopt.getopt(sys.argv[1:], cmdstring, [])
except getopt.GetoptError:
Usage()
sys.exit(1)

filelist = ''
inputfiles = ''
basedir = ''
for o, a in opts:
if o == '-V': #version
Version()
sys.exit()
elif o == '-h':
Usage()
sys.exit()
elif o == '-l':
filelist = a
elif o == '-i':
inputfiles = a
elif o == '-b':
basedir = a

if not basedir:
basedir = os.getcwd()

if inputfiles and filelist or len(args) < 1:
Usage()
sys.exit()

zipfile = args[0]
if not inputfiles and len(args) > 1:
fout = None
if filelist:
fout = file(filelist, 'w')

def visitor(path, arcname, f=fout):
if f:
f.write(arcname + '\n')

if len(args) == 2 and os.path.isdir(args[1]):
create(zipfile, args[1:], basedir, visitor)
else:
create(zipfile, args[1:], basedir, visitor=visitor)
if fout:
fout.close()
elif inputfiles and len(args) == 1:
lines = file(inputfiles).readlines()
files = [f.strip() for f in lines]
create(zipfile, files, basedir)

else:
Usage()
sys.exit()


def Usage():
print """Usage %s [options] zipfilename directories|filenames
%s -i listfile zipfilename

-V Show version
-h Show usage
-l Create a listinfo file
-i Input file list
-b Specify base directory
""" % (sys.argv[0], sys.argv[0])

def Version():
print """%s Copyleft GPL
Author: %s
Version: %s""" % (__appname__, __author__, __version__)

if __name__ == '__main__':
# a = ZFile('d:/aaaa.zip', 'w')
# a.addfile('d:/a.csv')
# a.addfile('d:/test/a.JPG')
# a.addfile('d:/test/mixin/main.py', 'main.py')
# files = ['d:/a.csv', 'd:/test/a.JPG', ('d:/test/mixin/main.py', 'main.py')]
## a.addfiles(files)
## a.close()
# create('d:/aaaa.zip', files)
# a = ZFile('d:/aaaa.zip')
# a.extract_to('d:/test/aaaa')
# extract('d:/aaaa.zip', 'd:/test/aaaa/aaaa')
main()

--
I like python!
UliPad <<The Python Editor>>: http://code.google.com/p/ulipad/
meide <<wxPython UI module>>: http://code.google.com/p/meide/
My Blog: http://www.donews.net/limodou

Zoom.Quiet

unread,
Feb 15, 2008, 11:49:56 PM2/15/08
to pyth...@googlegroups.com
http://wiki.woodpecker.org.cn/moin/MicroProj/2008-02-16
collected it!

2008/2/16 limodou <lim...@gmail.com>:

--
'''Time is unimportant, only life important!
过程改进乃是开始催生可促生靠谱的人的组织!
'''http://zoomquiet.org
博 @ http://blog.zoomquiet.org/pyblosxom/
维 @ http://wiki.woodpecker.org.cn/moin/ZoomQuiet
豆 @ http://www.douban.com/people/zoomq/
看 @ http://zoomq.haokanbu.com/
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Pls. usage OOo to replace M$ Office. http://zh.openoffice.org
Pls. usage 7-zip to replace WinRAR/WinZip. http://7-zip.org
You can get the truely Freedom 4 software.

Samuel Chi

unread,
Feb 16, 2008, 1:25:18 AM2/16/08
to pyth...@googlegroups.com
zlib.compress and decompress
据我的测试结果,C#里没有单纯的deflate和inflate两个函数.
zlib的官方下载包里面contrib\dotzlib是一个较好的.NET封装包.

在08-2-16,马踏飞燕 <honey...@gmail.com> 写道:

马踏飞燕

unread,
Feb 16, 2008, 3:11:15 AM2/16/08
to pyth...@googlegroups.com
C#官方确实没有deflate的压缩算法,现在大家用得最多的就是
ICSharpCode.SharpZipLib.Zip.Compression 这个第三方包里面的Deflater类。

其实我是打算做一个txt转umd格式的程序,但是我直接用zlib压缩出来的数据放到手机的掌上书院不能用,我比较了一下用mBookMaker生成出来的文件与我做的,就发现他用得deflate算法压缩的。

在 08-2-16,Samuel Chi<princeofd...@gmail.com> 写道:

Samuel Chi

unread,
Feb 16, 2008, 4:41:36 AM2/16/08
to pyth...@googlegroups.com
既然他是defalte,那你就直接inflate不就是了么

在08-2-16,马踏飞燕 <honey...@gmail.com> 写道:

马踏飞燕

unread,
Feb 18, 2008, 7:30:59 AM2/18/08
to pyth...@googlegroups.com
谢谢!
这段代码给我了启发,我看了zipfile的源代码,直接用了里面的一段。
经测试,压缩出来的内容确实和C#的那个组件包是一样的,但是,还是不能用在生成UMD上。

现在直接用C#写了,唉!Python也有不及的地方啊,要么就是我不及。。。

在 08-2-16,limodou<lim...@gmail.com> 写道:

Reply all
Reply to author
Forward
0 new messages