search
HomeBackend DevelopmentPython TutorialHow PYTHON generates ZIP files in memory

How PYTHON generates ZIP files in memory

Oct 18, 2016 pm 02:52 PM
pythonzip fileMemory

如题,代码如下:

class MemoryZipFile(object):
   def __init__(self):
       #创建内存文件
       self._memory_zip = StringIO.StringIO()
        
   def append_content(self, filename_in_zip, file_content):
       """
       description: 写文本内容到zip
       """
       zf = zipfile.ZipFile(self._memory_zip, "a", zipfile.ZIP_DEFLATED, False)
       zf.writestr(filename_in_zip, file_content)
       for zfile in zf.filelist: zfile.create_system = 0
       return self
         
   def append_file(self, filename_in_zip, local_file_full_path):
       """

description:写文件内容到zip

      注意这里的第二个参数是本地磁盘文件的全路径(windows:c/demo/1.jpg | linux: /usr/local/test/1.jpg)

      """

      zf = zipfile.ZipFile(self._memory_zip, "a", zipfile.ZIP_DEFLATED, False)

      zf.write(local_file_full_path, filename_in_zip)

      for zfile in zf.filelist: zfile.create_system = 0      

      return self

     

  def read(self):

      """

      description: 读取zip文件内容

      """

      self._memory_zip.seek(0)

      return self._memory_zip.read()

 

  def write_file(self, filename):

      """

      description:写zip文件到磁盘

      """

      f = file(filename, "wb")

      f.write(self.read())

      f.close()





使用方法如下:

        mem_zip_file = MemoryZipFile()
        mem_zip_file.append_content('mimetype', "application/epub+zip")
        mem_zip_file.append_content(&#39;META-INF/container.xml&#39;, &#39;&#39;&#39;<?xml version="1.0" encoding="UTF-8" ?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"> </container>&#39;&#39;&#39;);
        #追加磁盘上的文件内容到内存,注意这里的第二个参数是本地磁盘文件的全路径(windows:c/demo/1.jpg | linux: /usr/local/test/1.jpg)
        mem_zip_file.append_file("1.jpg", "c:\1.jpg")
  
  
        #将内存中的zip文件写入磁盘
        mem_zip_file.write_file("c:test.zip")
  
        #获取内存zip文件内容
        data = mem_zip_file.read()
  
        #上传到fdfs
        my_fdfs_client.upload_by_buffer(data, &#39;zip&#39;)


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you slice a Python array?How do you slice a Python array?May 01, 2025 am 12:18 AM

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Under what circumstances might lists perform better than arrays?Under what circumstances might lists perform better than arrays?May 01, 2025 am 12:06 AM

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

How can you convert a Python array to a Python list?How can you convert a Python array to a Python list?May 01, 2025 am 12:05 AM

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

What is the purpose of using arrays when lists exist in Python?What is the purpose of using arrays when lists exist in Python?May 01, 2025 am 12:04 AM

ChoosearraysoverlistsinPythonforbetterperformanceandmemoryefficiencyinspecificscenarios.1)Largenumericaldatasets:Arraysreducememoryusage.2)Performance-criticaloperations:Arraysofferspeedboostsfortaskslikeappendingorsearching.3)Typesafety:Arraysenforc

Explain how to iterate through the elements of a list and an array.Explain how to iterate through the elements of a list and an array.May 01, 2025 am 12:01 AM

In Python, you can use for loops, enumerate and list comprehensions to traverse lists; in Java, you can use traditional for loops and enhanced for loops to traverse arrays. 1. Python list traversal methods include: for loop, enumerate and list comprehension. 2. Java array traversal methods include: traditional for loop and enhanced for loop.

What is Python Switch Statement?What is Python Switch Statement?Apr 30, 2025 pm 02:08 PM

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

What are Exception Groups in Python?What are Exception Groups in Python?Apr 30, 2025 pm 02:07 PM

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

What are Function Annotations in Python?What are Function Annotations in Python?Apr 30, 2025 pm 02:06 PM

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment