Pythonでパスワード付きのzipファイルを解凍する - 珠玉の誤訳
のpython3版
import zipfile
def unzip_with_pwd(filename, path='.', pwd=b''):
with zipfile.ZipFile(filename, 'r') as zip_file:
try:
zip_file.extractall(path=path, pwd=pwd)
print('extraction is successful!')
except RuntimeError:
print('{} is wrong password!'.format(pwd))
if __name__ == "__main__":
unzip_with_pwd(filename="test.zip", pwd=b'nya')
Windowsで圧縮していると展開したファイルがLinux上で化けるので変換が必要
import zipfile
def unzip_with_pwd_ja(filename, path='.', pwd=b''):
with zipfile.ZipFile(filename, 'r') as zip_file:
try:
for info in zip_file.infolist():
info.filename = info.filename.encode('cp437').decode('cp932')
zip_file.extract(info, path=path, pwd=pwd)
print('extraction is successful!')
except RuntimeError:
print('{} is wrong password!'.format(pwd))
if __name__ == "__main__":
unzip_with_pwd_ja(filename="test.zip", pwd=b'nya')