Skip to content

Instantly share code, notes, and snippets.

@hisui
Created October 12, 2017 14:09
Show Gist options
  • Save hisui/90c2b3dd3685e16beb5f456dc536f68a to your computer and use it in GitHub Desktop.
Save hisui/90c2b3dd3685e16beb5f456dc536f68a to your computer and use it in GitHub Desktop.
import sys, os, itertools, collections, zipfile
if len(sys.argv) < 2:
sys.stderr.writelines("Usage: python ziptree.py <path-to-zip>")
sys.exit(-1)
Entry = collections.namedtuple('Entry', ['name', 'children'])
def tree_of_zip(path_to_zip, only_dir=False):
stack = [Entry("", [])]
with zipfile.ZipFile(path_to_zip) as src:
for name in sorted(src.namelist()):
parts = [""] + name.split("/")
count = 0
while count < min(len(parts[0:-1]), len(stack)) and parts[count] == stack[count].name: count += 1
stack = stack[0:count]
for dir in parts[count:-1]:
entry = Entry(dir, [])
stack[-1].children.append(entry)
stack.append(entry)
if not only_dir and parts[-1] != "":
stack[-1].children.append(Entry(parts[-1], []))
return stack[0]
def dump_tree(node, indent="", terminal=True):
sys.stdout.write(indent)
sys.stdout.write("└ " if terminal else "├ ")
print(node.name)
indent += " " if terminal else "│ "
for e in node.children:
dump_tree(e, indent, node.children[-1] == e)
dump_tree(
tree_of_zip(sys.argv[1])
._replace(
name = os.path.basename(sys.argv[1])
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment