【问题标题】:two pieces of python code creates zip archive one of two is broken两段 python 代码创建 zip 存档 两段之一损坏
【发布时间】:2019-10-04 13:47:14
【问题描述】:

最初我想动态创建 zip 文件并在 http 响应中返回它。我使用 python 3.7 lib zipfile。 我尝试了 io buffer 和 tmp dir,它们都没有创建有效的 zip 存档。存档仅在将其保存在光盘上时才打开 导入压缩文件 导入io

#==============================================
# V1

file_like_object = io.BytesIO()

myZipFile = zipfile.ZipFile(file_like_object, "w", compression=zipfile.ZIP_DEFLATED)
myZipFile.writestr(u'test.py', b'test')

tmparchive="zip1.zip"

out = open(tmparchive,'wb') ## Open temporary file as bytes
out.write(file_like_object.getvalue())
out.close()

r = open(tmparchive, 'rb')
print (r.read())
r.close()

#==============================================



# V2

tmparchive2 = 'zip2.zip'

myZipFile2 = zipfile.ZipFile(tmparchive2, "w", compression=zipfile.ZIP_DEFLATED)
myZipFile2.writestr(u'test.py', b'test')

r2 = open(tmparchive2, 'rb')
print (r2.read())
r2.close()

#====================================================

【问题讨论】:

    标签: python-3.x io zip


    【解决方案1】:

    最好像这样使用 上下文管理器

    import zipfile, io
    
    file_like_object = io.BytesIO()
    with zipfile.ZipFile(file_like_object, "w", compression=zipfile.ZIP_DEFLATED) as myZipFile:
        myZipFile.writestr(u'test.txt', b'test')
    
    # file_like_object.getvalue() are the bytes you send in your http response.
    

    我将它写入文件。这绝对是一个有效的 zip 文件。

    如果要打开存档,需要将其保存到磁盘。 Explorer 和 7-Zip 等应用程序无法读取存在于 python 进程中的 BytesIO 对象。他们只能打开保存在磁盘上的档案。

    调用print(r.read()) 不会打开存档。它只会打印构成您刚刚创建的小 zip 文件的字节。

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多