2014-05-17 255 views
3

在Go中,我们如何在不压缩的情况下将文件添加到zip压缩文件?将文件添加到zip压缩文件而不压缩

对于上下文,我正在跟随IBM tutorial创建一个epub zip文件。它示出了下面的Python代码:

import zipfile, os 

def create_archive(path='/path/to/our/epub/directory'): 
    '''Create the ZIP archive. The mimetype must be the first file in the archive 
    and it must not be compressed.''' 

    epub_name = '%s.epub' % os.path.basename(path) 

    # The EPUB must contain the META-INF and mimetype files at the root, so 
    # we'll create the archive in the working directory first and move it later 
    os.chdir(path)  

    # Open a new zipfile for writing 
    epub = zipfile.ZipFile(epub_name, 'w') 

    # Add the mimetype file first and set it to be uncompressed 
    epub.write(MIMETYPE, compress_type=zipfile.ZIP_STORED) 

    # For the remaining paths in the EPUB, add all of their files 
    # using normal ZIP compression 
    for p in os.listdir('.'): 
     for f in os.listdir(p): 
      epub.write(os.path.join(p, f)), compress_type=zipfile.ZIP_DEFLATED) 
    epub.close() 

在这个例子中,文件mimetype(其仅具有内容application/epub+zip)不能被压缩。

Go documentation确实提供了写入zip压缩文件的一个示例,但所有文件都被压缩。

回答

5

有两种方法可以将文件添加到文件zip.WriterCreate方法和CreateHeader。虽然Create只允许您指定文件名,但CreateHeader方法提供了更多的灵活性,包括设置压缩方法的能力。

例如:

w, err := zipwriter.CreateHeader(&zip.FileHeader{ 
    Name: filename, 
    Method: zip.Store, 
}) 

现在,您可将数据写入w一样从转到文档中的示例代码,它会被存储于zip文件,而无需压缩。

相关问题