Showing posts with label web. Show all posts
Showing posts with label web. Show all posts

Monday, March 30, 2009

python 动态生成 zip 文件

python 中处理 zip 文件

from zipfile import ZipFile

z = ZipFile('abc.zip', 'w')
z.write('abc.txt', 't/abc.txt')
z.writestr('t/abc2.txt', 'this text is from my')
z.close()


# 即时压缩

import os
from zipfile import ZipFile
from StringIO import StringIO

f = StringIO()
z = ZipFile(f, 'w')

def safewrite(f, *arg, **kw):
    if os.path.isfile(f):
        z.write(f, *arg, **kw)
    elif os.path.isdir(f):
        for root, dirs, files in os.walk(f):
            for f_ in files:
                z.write(os.path.join(root, f_))

safewrite('flash')
safewrite('abc.txt', 't/abc.txt')
z.writestr('t/abc2.txt', 'this text is from my')
z.close()


print 'Content-Type: application/zip'
print 'Content-Disposition: attachment; filename=abc.zip'
print

print f.getvalue()