简体   繁体   English

Python在动态文件系统中创建Zip文件

[英]Python Create Zip File in a Dynamic File System

I'm having trouble creating a zip in my file system which is dynamic depending on what's defined in the .env file. 我在文件系统中创建zip时遇到问题,该文件系统是动态的,具体取决于.env文件中定义的.env Can someone guide me through the correct way of writing the zip file? 有人可以指导我正确编写zip文件吗?

Here's what I've come up so far which is I know is incorrect. 到目前为止,这是我所知道的,这是不正确的。

import os
import zipfile
from fs import open_fs


def download_zip_report():
    try:
        fs = open_fs(os.getenv('UPLOAD_FOLDER').strip("'"))
        with fs.open('/', 'wb') as test_file:
            zf = zipfile.ZipFile('test2.zip', mode='w')
            zf.write('file.txt')
            zf.close()

    except Exception as e:
        logging.error(str(e))
        return Response(status=404)

I'm not sure what the file system package is used for but the appropriate way to write a zipfile is: 我不确定文件系统软件包的用途,但是编写zipfile的适当方法是:

from zipfile import ZipFile

with ZipFile('path/to/zipfile.zip', 'w') as zip_file:
    zip_file.write('path/to/file')

Bare in mind that "...ZipFile is also a context manager and therefore supports the with statement. In the example, myzip is closed after the with statement's suite is finished—even if an exception occurs.." (From zipfile — Work with ZIP archives documentation ) so you don't have to use zip.close() at the end. 切记: “ ... ZipFile也是上下文管理器,因此支持with语句。在本示例中,即使with语句发生,myzip也会在完成后关闭-即使发生异常。。” (来自zipfile-使用ZIP存档文档 ),因此您不必在末尾使用zip.close()。 Thus applies to all context manager in Python. 因此适用于Python中的所有上下文管理器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM