gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:36:36 24 4
gpt4 key购买 nike

我需要递归查找名称包含子字符串“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

关于python - 如何获取与子字符串匹配的文件夹名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48392381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com