简体   繁体   中英

Data Structure For Directory Tree in Python

I want to create a data structure that holds the full information for any arbitrary directory tree, addressed the by directory path. I envision something like this:

dirtree[ "/home/user" : { subdirs: [ "bin", "Desktop" ] , "files" : [ ".profile" , ".login" ]

or in a list form to have a initial point that is easily addressable:

dirtree[0][ "/home/user" : { subdirs: [ "bin", "Desktop" ] , "files" : [ ".profile" , ".login" ]

dirtree[1][ "/home/user/bin" : { subdirs: [ "Python" ] , "files" : [ "script1.py" , "script2.py" ]

Meaning that the items in the list would be a dict indexed by the full path of every directory, that contains two dicts, subdirs and files that both lists of the files and subdirectories in each directory.

I was thinking that the outer wrapper could be a list, so there is a starting point of the root of the directory tree in the 0th item, but I am not sure that is a must have. It would be quicker to traverse.

This is to hold all the information for a webserver

I got as far as a dict of lists, but how do I nest that inside another dist of directory full-paths?

>>> dir={ "subdirs":[] , "files":[] }
>>> dir
{'subdirs': [], 'files': []}

I am beginning with python, by the way.

I want to end up with something like dirtree{ "/home/username"}{"subdirs"}[] dirtree{ "/home/username"}{"files"}[]

Then I can start at the top and iterate down adding directories and files in as I find them, and keep the full directory subtree and be able to switch contexts to any directory in the sub-tree to generate a web page based on that for navigation in a web page.

 dirkey="/"
 subdirs=['d1', 'd2', 'd3', 'd4', 'd5', 'd6']
 files=['f1', 'f2', 'f3', 'f4', 'f5', 'f6']

 dir={ dirkey : { "subdirlist" : subdirs , "filelist" : files } }

 dir
 {'/': {'subdirlist': ['d1', 'd2', 'd3', 'd4', 'd5', 'd6'], 'filelist': ['f1', 'f2', 'f3', 'f4', 'f5', 'f6']}}

 dir["/"]
 {'/': {'subdirlist': ['d1', 'd2', 'd3', 'd4', 'd5', 'd6'], 'filelist': ['f1', 'f2', 'f3', 'f4', 'f5', 'f6']}}

 dir["/"]["subdirlist"]
 ['d1', 'd2', 'd3', 'd4', 'd5', 'd6']

 dir["/"]["filelist"]
 ['f1', 'f2', 'f3', 'f4', 'f5', 'f6']

 dir["/"]["filelist"][1]
 'f2'

 dir["/"]["filelist"][-1]
 'f6'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM