Skip to content

Instantly share code, notes, and snippets.

@jedy
Created April 7, 2020 04:01
Show Gist options
  • Save jedy/b0b35f5077435f49a115b873142b0d40 to your computer and use it in GitHub Desktop.
Save jedy/b0b35f5077435f49a115b873142b0d40 to your computer and use it in GitHub Desktop.
decompress ZIP file with encoding
import zipfile
import pathlib
import chardet
def unzip(file, path):
z = zipfile.ZipFile(file)
detector = chardet.UniversalDetector()
for i in z.infolist():
if i.flag_bits & 0x800 == 0:
detector.feed(i.filename.encode("cp437"))
if detector.done:
break
detector.close()
encoding = detector.result["encoding"]
for i in z.infolist():
if i.flag_bits & 0x800 == 0:
try:
n = pathlib.Path(path, i.filename.encode("cp437").decode(encoding))
except Exception:
n = pathlib.Path(path, i.filename)
else:
n = pathlib.Path(path, i.filename)
if i.is_dir():
if not n.exists():
n.mkdir(parents=True)
else:
with n.open('wb') as w:
w.write(z.read(i.filename))
z.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment