如何使用 Python3 创建最大兼容的 zip 文件?

How to create maximum compatible zip files with Python3?

我可以使用 Python3 包 zipfile 创建和读取存档,没有任何问题。但我无法使用其他程序打开该档案 - 无法在 Windows 10(内置提取器)或 GNU/Linux.

上打开

我的目标 是用 Python3 创建 zip 文件,几乎可以在每台机器和每个 zipper-programm 上打开。

在 XFCE 上使用 Windows10 archiver 或 XArchiver 的错误消息是不明确的。但是在 shell (Debian GNU/Linux 10) 上我可以看到这个

$ unzip the_archive.zip
Archive:  the_archive.zip
   skipping: in_zip.txt              need PK compat. v6.3 (can do v4.6)

这是 Python3 创建此类存档的代码

#!/usr/bin/env python3
import zipfile

# the file that will be zipped
with open('in_zip.txt', 'w') as f:
    f.write('foobar')

# create zip file
with zipfile.ZipFile('the_archive.zip', 'w',
                     compression=zipfile.ZIP_LZMA,
                     compresslevel=9) as zip_file:  # maximum
    zip_file.write('in_zip.txt')

您使用的 LZMA 压缩方法未得到广泛支持。以下摘自 zipfile 手册页。

Note The ZIP file format specification has included support for bzip2 compression since 2001, and for LZMA compression since 2006. However, some tools (including older Python releases) do not support these compression methods, and may either refuse to process the ZIP file altogether, or fail to extract individual files

为了获得最大的互操作性,请坚持 zipfile.ZIP_STOREDzipfile.ZIP_DEFLATED

接下来是您在 zip 文件中使用的文件名。尽管 zipfile 可以将 Unicode 文件名正确地存储在 zip 存档中,编码为 UTF8,但如果互操作性是一个关键因素,您希望继续使用 7 位 ASCII。此外,在 Windows 上要注意要避免的字符(和文件名)。有关详细信息,请参阅 What characters are forbidden in Windows and Linux directory names?

如果您别无选择并且需要存储非 7 位 ASCII 的文件名,请确保将它们正确编码为 UTF-8。 zip 文件唯一可移植的字符集是 7 位 ASCII 和 UTF-8

另一个需要注意的功能是 ZIP64 支持。现在大多数存档器都支持它,但有些图书馆不支持。只有当你处理的是 >4Gig 时你才会触发它,在这种情况下你没有太多选择。