Getting “TypeError: pwd: expected bytes, got str” when extracting zip file with password

孤街浪徒 提交于 2020-05-15 21:53:20

问题


I want to unzip a specific named file located in a specific directory.

The name of the file = happy.zip.
The location = C:/Users/desktop/Downloads.

I want to extract all the files to C:/Users/desktop/Downloads(the same location)

I tried:

import zipfile
import os
in_Zip = r"C:/Users/desktop/Downloads/happy.zip"
outDir = r"C:/Users/desktop/Downloads"
z = zipfile.ZipFile(in_Zip, 'r')
z.extractall(outDir, pwd='1234!')
z.close

But I got:

"TypeError: pwd: expected bytes, got str"


回答1:


In Python 2: '1234!' = byte string

In Python 3: '1234!' = unicode string

Assuming you are using Python 3, you need to either use b'1234!' or encode the string to get byte string using str.encode() this is useful if you have the password saved as a string passwd = '1234!' then you can use:

z.extractall(outDir, pwd=passwd.encode())

or use byte string directly:

z.extractall(outDir, pwd=b'1234!')


来源:https://stackoverflow.com/questions/46266555/getting-typeerror-pwd-expected-bytes-got-str-when-extracting-zip-file-with

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!