问题描述
我正在尝试在pyGTK中生成一个分层目录列表.
I am trying to generate a hierarchical directory listing in pyGTK.
目前,我有以下目录树:
Currently, I have this following directory tree:
/root
folderA
- subdirA
- subA.py
- a.py
folderB
- b.py
我编写了一个几乎可以正常工作的函数:
I have written a function that -almost- seem to work:
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)
这是我运行该应用程序时得到的:
This is what i get when i run the app:
我还认为我的函数效率低下,我应该使用os.walk(),因为它已经为此目的而存在.
I also think my function is inefficient and that i should be using os.walk(), since it already exists for such purpose.
我该怎么办?用pyGTK生成目录树的正确/最有效的方法是什么?
How can I, and what is the proper/most efficient way of generating a directory tree with pyGTK?
---编辑---- 我最终使用的有效代码块是:
---edit----the block of code i ended up using, that works, is:
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])
推荐答案
关于性能,这是一个常见问题解答.关于算法:到达subdirA
piter
指向subdirA
,在下次迭代时到达a.py
piter
仍指向subdirA
.
About the performance, this is a FAQ.About your algorithm: when you reach subdirA
piter
points to subdirA
, at the next iteration when you reach a.py
piter
still points to subdirA
.
如您所说,请使用os.walk
.
这篇关于如何在GtkTreeView小部件中列出目录层次结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!