The zipfile.ZipFile
documentation says that ZIP_DEFLATED
can be used as compression method only if zlib
is available, but neither zipfile
module specification nor zlib
module specification says anything about when zlib
might not be available, or how to check for its availability.
I work on Windows and when I install any version of Python, zlib
module is available. Is this different in Linux? Does zlib
need to be installed separately?
Also, what is the proper way to check for zlib
availability? Is import zlib
going to raise an ImportError
if it is not available?
In oher words, is this the correct way to use zipfile
?
try:
import zlib
except ImportError:
zlib = None
compression = zipfile.ZIP_STORED if zlib is None else zipfile.ZIP_DEFLATED
with zipfile.ZipFile(file, mode, compression) as zf:
...
sudo apt install python3.8
, zlib
will be installed as a dependency.zlib1g-dev
, (and this action is sometimes forgotten to do)
and then compile and install python as sudo make install
. Full instructions here
zlib
is not available import zlib
will raise exception, such as>>> import zlib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'zlib
There are examples of code like this in the Python standard library. e.g. in zipfile.py:
try:
import zlib # We may need its compression method
crc32 = zlib.crc32
except ImportError:
zlib = None
crc32 = binascii.crc32
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With