← 中文资源

简体中文版本

glob 按模式展开文件列表

glob 的 * 不跨目录分隔符,** 必须配 recursive=True 才会递归下钻;匹配结果顺序不确定,展示或测试前先排序才稳定。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

single: ['a.log']
recursive: ['a.log', 'other\\d.log', 'sub\\b.log']
txt: ['sub\\deep\\c.txt']

实现说明

glob 按模式展开文件列表的核心是函数 show。 循环只出现在 for rel in ("a.log", "sub/b.log", "sub/deep/c.txt", "other/d.log"),它的每次迭代处理一个元素。

使用要点

  • 每一步打印都带着自己的标签:single:、recursive:、txt:。
  • 值得导入的表面是 show;周围的辅助代码对片段是私有的。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 全部导入都来自标准库:glob、os、tempfile。 文件在加载时定义 show。

签名一览:def show(pattern, recursive=False)

核心语句

with open(path, "w", encoding="utf-8") as f:
    f.write("x")
def show(pattern, recursive=False):
    matches = glob.glob(os.path.join(root, pattern), recursive=recursive)
    return sorted(os.path.relpath(m, root) for m in matches)

代码示例

import glob
import os
import tempfile

# Build a small tree so the patterns have something real to match
with tempfile.TemporaryDirectory() as root:
    for rel in ("a.log", "sub/b.log", "sub/deep/c.txt", "other/d.log"):
        path = os.path.join(root, rel)
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w", encoding="utf-8") as f:
            f.write("x")

    def show(pattern, recursive=False):
        matches = glob.glob(os.path.join(root, pattern), recursive=recursive)
        return sorted(os.path.relpath(m, root) for m in matches)

    # Single star never crosses a directory separator
    print("single:", show("*.log"))
    # ** only descends when recursive=True is set
    print("recursive:", show("**/*.log", recursive=True))
    print("txt:", show("**/*.txt", recursive=True))