python - 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'
推荐阅读
- coldfusion - GSuite Admin API 不再适用于用户更新
- java - 如何在 .txt 文件上写入内容?
- angular - Angular 8 HttpClient 发布请求内容类型崩溃
- c++ - 如何打印 MergeSort 的所有中间步骤?
- android - 任务 ':app:packageRelease' 执行失败。值 (90354) > 0x0000ffff
- algorithm - 区间划分问题不同的方法 - 在最少数量的教室中安排讲座
- c# - 当两封电子邮件设置为回复标题时,回复功能在 GMAIL 中无法正常工作
- java - 当玩家移动到屏幕边缘时,如何让背景“切换”,并将它们传送回来,就好像在一个世界中移动一样
- python - 在 re.split 中使用管道会导致发生额外的拆分
- c# - 使 Int 每秒增加 x 值