Skip to main content
 首页 » 编程设计

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

2025年05月04日37shanyou

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

这是文件夹结构

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

我需要获取列表["Foo/Doug/CandyBar", "Foo/MilkBar"]

现在我可以使用 os.walk 和 glob.glob 并编写一堆循环来获取此列表,但我想知道我是否缺少更简单的技术。

请您参考如下方法:

也许使用生成器是个不错的选择

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 

缺点:

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

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

  • generators是one-shot forward(获取下一个元素后不能返回)

  • 如果你想保留一些“路径”,你必须将它存储在某个地方(比如列表),否则它会丢失

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

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