在Python中如何在gzip后为文件添加标题再写入

0 投票
1 回答
1027 浏览
提问于 2025-04-17 03:21

我正在尝试打开一个JavaScript文件,读取它,然后进行gzip压缩,最后把压缩后的内容写入另一个文件。我已经能做到这些了,但我想知道在写入压缩内容之前,怎么设置“Content-Encoding : gzip”。下面是我的代码:

import os, sys, mimetypes, zipfile, gzip, cStringIO
from optparse import OptionParser
def main():
    parser = OptionParser(usage='usage: %prog [options] src_file destination_file')
    parser.add_option('-x', '--expires', action='store_true', help='set far future expiry for all files')
    (options, args) = parser.parse_args()
    if len(args) != 2:
        parser.error("incorrect number of arguments")
    name = os.path.normpath(args[0])
    des_file = os.path.normpath(args[1])

    try:
        s_file = open(name, 'r')
        content = s_file.read()

        compressed = cStringIO.StringIO()
        gz = gzip.GzipFile(filename=name,  mode='w', fileobj=compressed)
        gz.write(content)
        gz.close()
        s_file.close()

        o_file = open(des_file, 'w')
        ##
        ## BEFORE WRITING THE CONTENT INTO A FILE HOW WE ADD THE Content-Encoding
        ##
        o_file.write(compressed.getvalue())
        o_file.close()

    except (IOError, os.error), why:
        print 'Failed to read the file', filename, '\n Exception:', why

1 个回答

0

这个通常是由提供文件的服务端决定的。 你的工作一般就是在创建文件时,设置正确的文件名后缀(在这个例子中是.gz),并且正确配置服务器。

撰写回答