如何获取与子字符串匹配的文件夹名称?

2024-10-03 23:29:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要递归地找到包含子字符串“Bar”的名称的文件夹下的所有路径。在Python 2.7中

这就是文件夹结构

Foo
|
------ Doug
|        |
|        --------CandyBar
|
---------MilkBar

我需要拿到名单["Foo/Doug/CandyBar", "Foo/MilkBar"]

现在我可以用os.步行以及全球。全球写一堆循环来得到这个列表,但我想知道我是否缺少一个更简单的技巧。你知道吗


Tags: 字符串路径文件夹名称列表fooosbar
2条回答

也许用发电机是个不错的选择

import os
res = (path for path,_,_ in os.walk("path") if "bar" in path)

注意:我使用“/”作为根路径,因为我的系统类似于unix。如果您使用的是windows,请将“/”替换为“C:\”(或任何您想要的内容)

优点:

  • 生成器使用的内存少得多,在计算时不会“阻塞”系统。你知道吗

示例:

# returns immediately
res = (path for path,_,_ in os.walk("/") if "bar" in path)

#I have to wait (who knows how much time)
res = [path for path,_,_ in os.walk("/") if "bar" in path]
  • 只需等待找到下一条“路径”所需的时间,就可以一次获得一条路径

示例:

res = (path for path,_,_ in os.walk("/") if "bar" in path)
# the for starts at no time
for path in res:
    # at each loop I only wait the time needed to compute the next path
    print(path) # see the path printed as it is computed 

res = [path for path,_,_ in os.walk("/") if "bar" in path]
# the for starts only after all paths are computed
for path in res:
    # no wait for each loop.
    print(path) # all paths printed at once 
  • 如果您想保留找到零件的“路径”,可以将其存储在列表中,并且只保留您感兴趣的“路径”(较少的内存使用)

示例:

res = (path for path,_,_ in os.walk("/") if "bar" in path)
path_store = []
for path in res:
    # I'm only interested in paths having odd length
    # at the end of the loop I will use only needed memory
    if(len(path)%2==1):
        path_store.append(path)
  • 如果在某个时候你已经完成了并且你对寻找更多的“路径”不感兴趣,你可以在任何时候停下来,为所有没有计算的路径节省时间

示例:

res = (path for path,_,_ in os.walk("/") if "bar" in path)
path_store = []
count = 10
for path in res:
    # I'm only interested in paths having odd length
    if(len(path)%2==1):
        count -= 1
        path_store.append(path)
        # I'm only interested in the first 10 paths.
        # Using generator I waited only for the computation of those 10 paths.
        # Using list you will always wait for the computation for all paths
        if( count <= 0 ):
            break

缺点:

  • 不能对生成器使用索引。你只能得到下一个项目。

  • 如果您想要一个同时包含所有路径的列表,则必须将其转换为一个列表(因此最好使用列表理解)

  • 生成器只向前一步(获取下一个元素后不能返回)

  • 如果要保留某些“路径”,必须将其存储在某个位置(如列表),否则它将丢失

在代码中,每次迭代都会丢失路径。 循环结束时,res已耗尽,不再可用。 我必须将我感兴趣的路径存储在列表路径存储中。你知道吗

path_store = []
for path in res:
    # I'm only interested in paths having odd length
    if(len(path)%2==1):
        path_store.append(path)
path = next(res) # Error StopIteration

试试这个:

import os
[x for x, _, _ in os.walk("path") if "bar" in x and os.path.isdir(x)]

相关问题 更多 >