【问题标题】:Recursively expand and search pattern of specific subdirectories递归扩展和搜索特定子目录的模式
【发布时间】:2015-06-16 21:35:01
【问题描述】:

我正在寻找在 python 中搜索特定子目录的选项。

例如这样的目录结构:

some_files/
     common/
     2009/
     2010/
     2011/
     ...

我只想在以 2 开头的子目录中搜索,因此它必须类似于“some_files/2*”。我认为使用 glob.glob 和 os.walk() 一定可以,但我无法让它工作。

现在我使用:

files = [os.path.join(dirpath, f)
                for dirpath, dirnames, files in os.walk(d)
                for f in files if f.endswith(ext)]

但这不符合特定需求。

谁能帮帮我,不胜感激!

【问题讨论】:

  • and os.path.join('some_files', '2') in dirpath 之类的有什么问题?
  • 我正在开发的工具在用户指定的位置查找特定文件。这些位置在配置文件中指定。所以他们可以说,你可以查看这个文件夹(some_files/),然后它也会搜索所有子目录。我想为用户提供仅在特定子目录中搜索的选项,使用类似 somefiles/2* 的语句。如果我理解正确,您提供的选项将不支持该选项。如果我错了,请纠正我:)
  • 为什么它不起作用?它只是检查是否在路径字符串中找到了指定的字符串。
  • 你想对 'some_files/2011/foo' 和 'some_files/bar/2011' 等目录中包含的文件做什么?
  • 你的意思是“(递归地)扩展和搜索(通配符)特定子目录的模式”。这不仅仅是说“特定子目录”。为了清楚起见,我编辑了标题。

标签: python path filepath subdirectory wildcard-expansion


【解决方案1】:

我会使用pathlib现在是 Python3 标准库的一部分)这样做:

from pathlib import Path

for subpath in Path().glob("2*):
    for file in subpath.glob("*.ext"):
        # ...

更新:pathlib 也可用于 Python 2.x(它已向后移植并发布到 Python Package Index)。简单地说:

$ pip install pathlib

【讨论】:

  • pathlib 2.7+也可以使用,只需要手动安装
【解决方案2】:

您可以使用 glob 和 dirpath 来查找匹配的目录:

from glob import iglob
import os

files = []
ext = "py"
for dirpath, dirnames, file in os.walk(path):
    match = next(iglob(os.path.join(dirpath, "2*")),"")
    if match:
        files.extend(iglob(os.path.join(match,"*.{}".format(ext))))
print(files)

或者如果你真的想要一个列表组合:

files = [f for dirpath, dirnames, file in os.walk(path) for f in
         iglob(os.path.join(next(iglob(os.path.join(dirpath, "2*")),
                                 '\\\\'), "*.{}".format(ext)))]
print(files)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 2013-06-17
    相关资源
    最近更新 更多