如何在Python中为压缩的zip文件设置密码
我在尝试给一个压缩文件设置密码时遇到了这个错误。下面是我得到的代码和错误信息。请给我一个正确做法的例子。
- 这只是脚本中设置密码的部分... 整个脚本太长了,无法全部贴出来。
代码:
password = "dog"
password = zipfile.setpassword(pwd)
Error received when hitting the password part of the script.
-------------------------------------------
Traceback (most recent call last):
File "C:\Users\Owner\Desktop\ZIP-IT\ZIP IT.py", line 86, in <module>
start()
File "C:\Users\Owner\Desktop\ZIP-IT\ZIP IT.py", line 54, in start
compress()
File "C:\Users\Owner\Desktop\ZIP-IT\ZIP IT.py", line 70, in compress
password = zipfile.setpassword(pwd)
AttributeError: 'module' object has no attribute 'setpassword'
2 个回答
-1
你需要引用特定的压缩包,而不是整个模块。
zpf = zipfile.ZipFile('your file path')
password = "dog"
password = zpf.setpassword(pwd)
1
你在用Python 2.6或更高版本吗?
ZipFile.setpassword(pwd)
这个方法可以把pwd设置为解压加密文件的默认密码。
这个功能在2.6版本中新增。
根据Python zipfile的文档,它们在开头提到可以“解密ZIP压缩包中的加密文件,但目前无法创建加密文件。”