LoginSignup
3
4

More than 3 years have passed since last update.

pythonでパスワード付きのzipファイルを展開する

Posted at

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')
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4