2011-09-29 60 views
0

我想打开一个javascript文件,读取它,gzip它,然后将其写回到另一个文件..能够做到所有这些..但如何可以设置“内容编码:gzip”写入压缩内容之前...这里是代码:在Python中如何在写入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 
+0

o_file.write(“Content-Encoding:.....”)??? – rocksportrocker

+0

嗯,这只是增加了一个额外的行gzip'ed文件..不真的把它添加到文件头! –

+7

没有这样的想法作为文件的内容编码。这是一个HTTP标头。 – jterrace

回答

0

这通常是由whatever is serving the file.确定你的工作通常仅限于设置正确的文件扩展名(.gz在这种情况下)创建文件并正确配置服务器时。