为什么 7-zip 不解码 zlib.compress() 编码的内容?

Why does 7-zip not decode what is encoded by zlib.compress()?

在下面的Python(3.10)程序中testCompress.py,作为测试输入,源代码本身应用 zlib 压缩,并应在 Windows 10 上使用 7-zip (20.00 alpha) 解压缩。但它失败了.不接受压缩字节作为存档。输出在程序下方给出。

这是节选。我真正的问题是,使用 Java [=36 解压缩 Python-压缩文件=]ZipInputStream。他们还证明这些字节不是存档。

from tempfile import gettempdir
from zlib import compress
from subprocess import run

filename=r"testCompress.py"
zipname = gettempdir() + r"\zipped.zip"
unzippedname = gettempdir() + r"\unzipped.txt"
unzip = r'"C:\Program Files-Zipz.exe" x ' + zipname

# zip using zlib

with open(filename,"r") as f:
    text = f.read()
b = bytes(text,"ascii")
bcompressed = compress(b)
with open(zipname,"wb") as f:
    f.write(bcompressed)
    f.close()

# unzip using 7-zip
print("now unzipping on cmd level", unzippedname)
run(unzip, shell=True)

导致输出:

PS C:\Users\ngong\python-workspace> & C:/Users/ngong/AppData/Local/Programs/Python/Python310/python.exe c:/Users/ngong/python-workspace/xslt/testCompress.py
unzipping C:\Users\NGONG\AppData\Local\Temp\unzipped.txt

7-Zip 20.00 alpha (x64) : Copyright (c) 1999-2020 Igor Pavlov : 2020-02-06

Scanning the drive for archives:
1 file, 9041 bytes (9 KiB)

Extracting archive: C:\Users\NGONG\AppData\Local\Temp\zipped.zip
ERROR: C:\Users\NGONG\AppData\Local\Temp\zipped.zip
C:\Users\NGONG\AppData\Local\Temp\zipped.zip
Open ERROR: Can not open the file as [zip] archive


ERRORS:
Is not archive

Can't open as archive: 1
Files: 0
Size:       0
Compressed: 0
PS C:\Users\ngong\python-workspace> 

用 gzip 交换 Python 模块 zlib 不能解释错误,但可以作为解决方法。

from tempfile import gettempdir
import gzip
from subprocess import run

filename=r"testGzip.py"
zipname = gettempdir() + r"\zipped.gz"
unzippedname = gettempdir() + r"\unzipped.txt"
unzip = r'"C:\Program Files-Zipz.exe" x ' + zipname

# zip using zlib

with gzip.open(zipname,"wb") as gz:
    with open(filename,"r") as f:
        gz.write( bytes(f.read(), "utf-8") )
        gz.close()

# unzip using 7-zip
print("now unzipping on cmd level", unzippedname)
run(unzip, shell=True)

导致预期的输出:

PS C:\Users\ngong\python-workspace> & C:/Users/ngong/AppData/Local/Programs/Python/Python310/python.exe c:/Users/ngong/python-workspace/testGzip.py
now unzipping on cmd level C:\Users\NGONG\AppData\Local\Temp\unzipped.txt

7-Zip 20.00 alpha (x64) : Copyright (c) 1999-2020 Igor Pavlov : 2020-02-06

Scanning the drive for archives:
1 file, 305 bytes (1 KiB)

Extracting archive: C:\Users\NGONG\AppData\Local\Temp\zipped.gz
--
Path = C:\Users\NGONG\AppData\Local\Temp\zipped.gz
Type = gzip
Headers Size = 17

Everything is Ok

Size:       484
Compressed: 305

zlib.compress() 将始终生成 zlib 流。在 Java 方面,您显然会寻找 gzip 流或 zip 文件。这是三个不同的东西。

您可以在 Python 中使用 zlib.compressobj() 来生成 gzip 流。 (有关如何请求的信息,请参阅文档。)

请参阅 this answer 了解这三种格式的一些背景知识。