在Python中,如何在gzip之后在写入文件之前添加文件头
我正在尝试打开一个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
I am trying to open a javascript file, read it, gzip it and then write it back to another file.. able to do all that.. but how can set the "Content-Encoding : gzip" before writing the compressed content... here is the code:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这通常由提供文件的内容决定。您的工作通常是仅限于在创建文件并正确配置服务器时设置正确的文件扩展名(在本例中为
.gz
)。That is usually determined by whatever is serving the file. Your job is usually limited to setting the correct file name extension (
.gz
in this case) when you create the file and configuring the server properly.