Created
May 23, 2018 18:39
-
-
Save xinhaoyuan/04bb4818fbaf944e75767f14e3d6960e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env python | |
import zipfile | |
import os | |
import subprocess | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument("-f", type = str, dest = "filename", help = "filename") | |
parser.add_argument("-e", action = "store_true", dest = "to_extract", help = "To extract") | |
parser.add_argument("--from", type = str, dest = "orig_encoding", help = "encoding of the archive") | |
parser.add_argument("--to", type = str, dest = "sys_encoding", help = "encoding of the system") | |
args = parser.parse_args() | |
def ensure_dirs(path): | |
dirname = os.path.dirname(path) | |
if len(dirname) == 0: | |
return | |
subprocess.check_call(["mkdir", "-p", dirname]) | |
z = zipfile.ZipFile(args.filename, "r") | |
for fi in z.infolist(): | |
converted_filename = fi.filename.decode(args.orig_encoding).encode(args.sys_encoding) | |
if args.to_extract: | |
print("Extracting {}".format(converted_filename)) | |
f = z.open(fi.filename, "r") | |
ensure_dirs(converted_filename) | |
if converted_filename.endswith("/"): | |
continue | |
with open(converted_filename, "w") as t: | |
buf_size = 4096 | |
while True: | |
buf = f.read(buf_size) | |
if len(buf) == 0: | |
break | |
t.write(buf) | |
else: | |
print(converted_filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment