在Python中,如何在写入文件之前在gzip之后添加文件头
我试图打开一个javascript文件,读取它,gzip它,然后写回另一个文件。。我能做到这一切。。但是如何在编写压缩内容之前设置“contentencoding:gzip”。。。代码如下:在Python中,如何在写入文件之前在gzip之后添加文件头,python,gzip,content-encoding,Python,Gzip,Content Encoding,我试图打开一个javascript文件,读取它,gzip它,然后写回另一个文件。。我能做到这一切。。但是如何在编写压缩内容之前设置“contentencoding:gzip”。。。代码如下: import os, sys, mimetypes, zipfile, gzip, cStringIO from optparse import OptionParser def main(): parser = OptionParser(usage='usage: %prog [options]
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
这通常由您的作业决定,通常仅限于在创建文件并正确配置服务器时设置正确的文件扩展名(
.gz
) o_file.write(“内容编码:…”)???嗯,这只是在gzip文件中添加了一行额外的内容。。不会真正将其添加到文件头中!没有像文件内容编码这样的想法。这是HTTP头。@jterrace谢谢!刚用过urllib2