1
我想在pyGTK中生成一个分层目录列表。如何列出GtkTreeView小部件中的目录层次结构?
目前,我有这个下面的目录树:
/root
folderA
- subdirA
- subA.py
- a.py
folderB
- b.py
我写了-almost-似乎工作的函数:
def go(root, piter=None):
for filename in os.listdir(root):
isdir = os.path.isdir(os.path.join(root, filename))
piter = self.treestore.append(piter, [filename])
if isdir == True:
go(os.path.join(root, filename), piter)
这是我所得到的,当我运行应用程序:
我也觉得我的功能是低效的,而且我应该使用os.walk(),因为它已经为此目的而存在。
我该怎么做,以及用pyGTK生成目录树的正确/最有效的方法是什么?
---编辑---- 我结束了使用,这样的作品,是代码块:
parents = {}
for dir, dirs, files in os.walk(root):
for subdir in dirs:
parents[os.path.join(dir, subdir)] = self.treestore.append(parents.get(dir, None), [subdir])
for item in files:
self.treestore.append(parents.get(dir, None), [item])