I have a zipfile in (sav.zip) and I'm trying to set a password for it:
zf = zipfile.ZipFile("sav.zip")
zf.setpassword("1234")
but I get a TypeError: expected Bytes, got str
.
Where's my mistake?
It is not mentioned in the documentation, but on Python 3, the password should be bytes
, not str
. So:
zf.setpassword(b"1234")
Note that the password is only used for reading, not writing! See the docstring for ZipFile.open
in Python 3.
The ZipFile
class can read "pkzip 2.0" encryption, which is not considered very strong (it has known weaknesses [pdf]). That could probably be the reason that writing them is not currently (as of Python 2.7.13 and 3.6) implemented in Python.
Note: The protection afforded by a password on a zipfile might not very strong, depending on what you want to use it for. An attacker can e.g. replace a password-protected entry in a zipfile without knowing the password! See e.g. this answer on security.stackexchange.
Note2: More recent versions of e.g. winzip can use AES to encrypt the contents of zipped files. AFAIK, Python cannot read those.