我正在用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]
Run Code Online (Sandbox Code Playgroud)
但是当我用 …