os.walk 但每个目录都有前置和后置操作?

发布于 2024-12-10 09:32:56 字数 491 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

∞觅青森が 2024-12-17 09:32:56

如果您不想自己编写简单的递归函数,则可以使用自己的堆栈:

stack = []
for root, dirs, files in os.walk("foo"):
    while stack and not root.startswith(stack[-1]):
        print "post-action on", stack.pop()
    print "pre-action on", root
    stack.append(root)
while stack:
    print "post-action on", stack.pop()

不过,编写自己的函数可能会提供更具可读性的代码:

def walk(dir):
    print "pre-action on", dir
    for name in os.listdir(dir):
        fullname = os.path.join(dir, name)
        if os.path.isdir(fullname):
            walk(fullname)
    print "post-action on", dir

If you don't want to write a simple recursive function yourself, you can use your own stack:

stack = []
for root, dirs, files in os.walk("foo"):
    while stack and not root.startswith(stack[-1]):
        print "post-action on", stack.pop()
    print "pre-action on", root
    stack.append(root)
while stack:
    print "post-action on", stack.pop()

Writing your own function probably gives more readable code, though:

def walk(dir):
    print "pre-action on", dir
    for name in os.listdir(dir):
        fullname = os.path.join(dir, name)
        if os.path.isdir(fullname):
            walk(fullname)
    print "post-action on", dir
抱猫软卧 2024-12-17 09:32:56

简而言之,你不能。图书馆没有提供任何这样做的选项。但是,您可以通过设置 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文