Created
February 18, 2016 07:50
-
-
Save nailuoGG/e2fdada0d4192bec0246 to your computer and use it in GitHub Desktop.
内存中进行压缩文件操作
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# !/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
__author__ = 'nailuoGG' | |
import os | |
from zipfile import ZipFile, ZIP_DEFLATED | |
import io | |
class InMemoryZip: | |
""" 在内存中进行压缩文件的操作 | |
data可以来自于网络或者磁盘io | |
""" | |
def __init__(self, data=None): | |
if data: | |
self.set_data(data) | |
else: | |
self.in_memory = io.BytesIO() | |
def get_data(self): | |
if self.in_memory.seek(0): | |
return self.in_memory.read() | |
def set_data(self, data): | |
self.in_memory = io.BytesIO() | |
self.in_memory.write(data) | |
def append(self, path_and_name): | |
""" 将文件或者文件夹添加到内存中的压缩文档 | |
:param path_and_name: | |
:return: | |
""" | |
zf = ZipFile(self.in_memory, 'a', ZIP_DEFLATED, False) | |
if os.path.isfile(path_and_name): | |
zf.write(path_and_name) | |
else: | |
path = path_and_name | |
for root, folders, files in os.walk(path_and_name): | |
for file in files: | |
full_name = os.path.join(root, file) | |
zf.write(full_name) | |
zf.close() | |
def save_as(self, path_and_name="archive.zip"): | |
""" 将文件存入磁盘 | |
:param path_and_name: | |
:return: | |
""" | |
with open(path_and_name, 'wb') as file: | |
file.write(self.get_data()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment