os.walk 但每个目录都有前置和后置操作?
Python的 os.walk 函数几乎是我想要的,但我需要对每个目录执行遍历前和遍历后操作。
例如,如果树是
foo/
foo/bar/
foo/bar/baz/
foo/quux/
,那么我想做这个序列:
pre-action on foo/
pre-action on foo/bar/
pre-action on foo/bar/baz/
post-action on foo/bar/baz/
post-action on foo/bar/
pre-action on foo/quux/
post-action on foo/quux/
post-action on foo/
我该怎么做? (无需编写我自己的函数来执行此操作)
Python's os.walk function is almost what I want, but I need to do a pre- and post-traversal action for each directory.
e.g. if the tree is
foo/
foo/bar/
foo/bar/baz/
foo/quux/
then I want to do this sequence:
pre-action on foo/
pre-action on foo/bar/
pre-action on foo/bar/baz/
post-action on foo/bar/baz/
post-action on foo/bar/
pre-action on foo/quux/
post-action on foo/quux/
post-action on foo/
How can I do this? (w/o writing my own function to do so)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不想自己编写简单的递归函数,则可以使用自己的堆栈:
不过,编写自己的函数可能会提供更具可读性的代码:
If you don't want to write a simple recursive function yourself, you can use your own stack:
Writing your own function probably gives more readable code, though:
简而言之,你不能。图书馆没有提供任何这样做的选项。但是,您可以通过设置
topdown=True
[链接]。这可以让您仅对搜索中的某些目录进行操作。文档中给出了最好的示例。这可能会解决你的问题。In short, you can't. The library doesn't give any options to do so. However, you can limit what walk actually returns to you, via setting
topdown=True
[link]. This can allow you to only act on some of the directories in your search. The best examples are given in the docs. This might solve your problem.