我正在用Python编写一个程序,在这个程序中,我需要与“假想的”路径(即在实际文件系统中不存在也不会存在的路径)进行交互,并且我需要能够listdir
像正常情况一样返回它们(path['directory']
会像os.listdir()
一样返回目录中的每一项)。你知道吗
我提出的解决方案是将字符串路径列表转换为字典。我提出了这个递归函数(它在一个类中):
def DoMagic(self,paths):
structure = {}
if not type(paths) == list:
raise ValueError('Expected list Value, not '+str(type(paths)))
for i in paths:
print(i)
if i[0] == '/': #Sanity check
print('trailing?',i) #Inform user that there *might* be an issue with the input.
i[0] = ''
i = i.split('/') #Split it, so that we can test against different parts.
if len(i[1:]) > 1: #Hang-a-bout, there's more content!
structure = {**structure, **self.DoMagic(['/'.join(i[1:])])}
else:
structure[i[1]] = i[1]
但是当我以['foo/e.txt','foo/bar/a.txt','foo/bar/b.cfg','foo/bar/c/d.txt']
作为输入运行它时,我得到:
{'e.txt': 'e.txt', 'a.txt': 'a.txt', 'b.cfg': 'b.cfg', 'd.txt': 'd.txt'}
我希望能够path['foo']['bar']
获取foo/bar/
目录中的所有内容。你知道吗
编辑:
更理想的产出是:
{'foo':{'e.txt':'e.txt','bar':{'a.txt':'a.txt','c':{'d.txt':'d.txt'}}}}
这个怎么样。它可以得到您想要的输出,但是树结构可能更干净。你知道吗
输出:
通过字典实现的简单树不就足够了吗? 你的实现似乎有点多余。很难说文件属于哪个文件夹。你知道吗
https://en.wikipedia.org/wiki/Tree_(data_structure)
如果你需要额外的东西,
pypi
上有很多lib。 treelib在pathlib中也有
Pure paths
。你知道吗相关问题 更多 >
编程相关推荐