如何在 GtkTreeView 小部件中列出目录层次结构?
我正在尝试在 pyGTK 中生成分层目录列表。
目前,我有以下目录树:
/root
folderA
- subdirA
- subA.py
- a.py
folderB
- b.py
我编写了一个几乎可以工作的函数:
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])
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:
I also think my function is inefficient and that i should be using os.walk(), since it already exists for such purpose.
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])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关于性能,这是常见问题解答 。
关于你的算法:当你到达
subdirA
时,piter
指向subdirA
,在下一次迭代时,当你到达a.py
时>piter
仍然指向subdirA
。正如您所说,使用 os.walk。
About the performance, this is a FAQ.
About your algorithm: when you reach
subdirA
piter
points tosubdirA
, at the next iteration when you reacha.py
piter
still points tosubdirA
.As you said, use
os.walk
.