2

I'm using zipfile and tarfile Python modules to open, extract and compress archives.
I need to display the archive structure in a QTreeWidget, and I don't know how to go on. To get the infos I use the function infos(path) from this file. I would like to obtain something like this (from Ark):
alt text

For example, if I receive this filenames: ('GCI/PyFiles/prova3.py', 'GCI/', 'GCI/PyFiles/', 'GCI/Screenshots/', 'GCI/prova2.py', 'prova.py'), I'd like to obtain this:

- prova.py
- GCI/
    |
    |- prova2.py
    |- PyFiles/
             |- prova3.py
    |- Screenshots/

in my QTreeWidget.

Thank you, rubik

rubik
  • 8,814
  • 9
  • 58
  • 88

1 Answers1

1

I'm not sure how QTreeWidget wants it's data offhand, but here is a (possibly bad way) to build the structure in memory.

x = ('GCI/PyFiles/prova3.py', 'GCI/', \
     'GCI/PyFiles/', 'GCI/Screenshots/', \
     'GCI/prova2.py', 'prova.py')

structure = {}
for fn in x:
    path = fn.split('/')

    tmpd = structure
    for p in path[:-1]:
        try:
            tmpd = tmpd[p]
        except KeyError:
            tmpd = tmpd[p] = {}

    tmpd[path[-1]] = None

This will give you a dictionary structure that for each key is either another dictionary (representing a folder) or None representing that the key is a file.

The better way to do this would create a class like this:

class Node(object):
    def __init__(self):
        self.dirs = {}
        self.files = []

or something like that which you can populate. If I remember correctly from my QT programming days, the QTreeWidget wants a datasource so you basically could figure out what that source looks like and populate it appropriately. There's also probably the option to do this,

[sp for _,sp in sorted(
         (len(splitpath),splitpath) for splitpath in
            (path.split('/') for path in x)
         )
    ]

which would return you:

[['prova.py'], ['GCI', ''], ['GCI', 'prova2.py'], 
 ['GCI', 'PyFiles', ''], ['GCI', 'PyFiles', 'prova3.py'], 
 ['GCI', 'Screenshots', '']]
milkypostman
  • 2,955
  • 27
  • 23