Created
May 18, 2014 07:34
-
-
Save hideaki-t/c42a16189dd5f88a955d to your computer and use it in GitHub Desktop.
unzipping a zip file with non-utf8 encoding by Python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import zipfile | |
import sys | |
from pathlib import Path | |
def unzip(f, encoding, v): | |
with zipfile.ZipFile(f) as z: | |
for i in z.namelist(): | |
n = Path(i.encode('cp437').decode(encoding)) | |
if v: | |
print(n) | |
if i[-1] == '/': | |
if not n.exists(): | |
n.mkdir() | |
else: | |
with n.open('wb') as w: | |
w.write(z.read(i)) | |
if __name__ == '__main__': | |
for i in sys.argv[1:]: | |
unzip(i, 'cp932', 1) |
it works well.
but why cp437
?
and why not ZipInfo.is_dir
to test if it is directory?
cp437: see https://github.com/python/cpython/blob/0d70227e419ab78c44d81b4ea6ae8aaf769470e6/Lib/zipfile.py#L1332-L1336
is_dir: I don't remember. but ZipInfo.is_dir does the same https://github.com/python/cpython/blob/0d70227e419ab78c44d81b4ea6ae8aaf769470e6/Lib/zipfile.py#L534-L536
cool!
Not robust enough, but still worked like a charm. Inspired me to enhance a new version of this.
Incredible! I struggled an hour for this.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks