下面的脚本只扫描目标目录的直接子项,不进入子目录;将普通文件中后缀为 .md 的文件按文件名排序,再以 UTF-8 读取。目录参数可选,省略时使用当前目录。
完整脚本
import argparse
from pathlib import Path
parser = argparse.ArgumentParser(description="按文件名读取 Markdown 文件")
parser.add_argument("directory", nargs="?", default=".", help="待扫描目录,默认当前目录")
args = parser.parse_args()
directory = Path(args.directory)
if not directory.exists() or not directory.is_dir():
raise FileNotFoundError(f"目录不存在或不是目录:{directory}")
files = sorted(
(path for path in directory.iterdir()
if path.is_file() and path.suffix == ".md"),
key=lambda path: path.name,
)
for path in files:
with path.open("r", encoding="utf-8") as file:
print(f"--- {path.name} ---")
print(file.read())
运行与检查
将代码保存为 scan_md.py。例如目录结构如下:
docs/
├── a.md
├── b.md
└── sub/
└── c.md
运行 python scan_md.py docs,输出依次包含 a.md、b.md 的文件名和正文;sub/c.md 不会纳入,因为 Path.iterdir() 只产生目录的直接子项。省略参数运行 python scan_md.py 则扫描当前目录。
路径不存在或指向的不是目录时,脚本主动抛出带路径的 FileNotFoundError。若没有匹配的 Markdown 文件,扫描列表为空,不会读取子目录内容。