You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何使用glob筛选含指定字符且排除含其他特定字符的文件

问题原因

你使用的glob语法中[!_1]属于单字符匹配规则,仅能排除文件名倒数第二位为_、最后一位为1的情况,无法覆盖「下划线+任意数字」的多字符排除场景,因此会漏过滤_2、_3这类结尾的文件。

解决方案

方案1:glob全匹配后二次过滤(兼容性最好,逻辑直观)

先匹配所有Batch_开头的xlsx文件,再做规则过滤即可:

import glob
import os

root_path = "C:\\Users\\Users\\Desktop\\Data\\"
# 先匹配所有Batch开头的xlsx文件
all_candidate = glob.glob(os.path.join(root_path, "**/Batch_*.xlsx"), recursive=True)
# 过滤排除以下划线加数字结尾的文件
result = [
    file for file in all_candidate
    # 取最后一段下划线后的内容,去掉后缀后判断是否为纯数字
    if not file.removesuffix(".xlsx").split("_")[-1].isdigit()
]

运行后result变量就会仅返回你需要的Batch_123.xlsx和Batch_456.xlsx两个文件。

方案2:正则匹配(规则更灵活)

如果需要更复杂的匹配规则,可以配合正则实现:

import glob
import os
import re

root_path = "C:\\Users\\Users\\Desktop\\Data\\"
# 正则规则:排除_加数字加.xlsx结尾的文件
filter_pattern = re.compile(r"_\d+\.xlsx$")
all_xlsx = glob.glob(os.path.join(root_path, "**/Batch_*.xlsx"), recursive=True)
result = [file for file in all_xlsx if not filter_pattern.search(file)]

内容的提问来源于stack exchange,提问作者BBBBBBBB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 12:36:02