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

Python如何从文件名扩展名前的最后位置提取年份

文件名年份提取解决方案

核心匹配逻辑:你的文件命名规律为四位年份固定位于扩展名前,且与前面的文件名内容以下划线分隔,可以通过以下几种常用方案实现提取:


Python 实现

方案1:正则匹配(适配性更强)

import os
import re

file_list = [
    "godzilla_2012.txt",
    "king_arthur_legend_of_the_sword_2016.txt",
    "Teenage_Mutant_ninja_turtle_2017.txt"
]
extracted_years = []

for filename in file_list:
    # 直接匹配扩展名前的四位数字,避免文件名其他位置出现四位数字导致误匹配
    match_res = re.search(r"_(\d{4})\.[^.]+$", filename)
    if match_res:
        extracted_years.append(match_res.group(1))

print(extracted_years)
# 输出结果:['2012', '2016', '2017']

方案2:字符串分割(逻辑更简单,适合命名完全规范的场景)

import os

file_list = [
    "godzilla_2012.txt",
    "king_arthur_legend_of_the_sword_2016.txt",
    "Teenage_Mutant_ninja_turtle_2017.txt"
]
extracted_years = []

for filename in file_list:
    # 先去掉扩展名,按下划线分割取最后一段即为年份
    name_no_ext = os.path.splitext(filename)[0]
    year = name_no_ext.split("_")[-1]
    extracted_years.append(year)

Shell 实现(Linux/macOS 环境)

遍历当前目录下所有txt文件提取年份:

for f in *.txt; do echo $f | grep -oE '[0-9]{4}(?=\.txt$)'; done

PowerShell 实现(Windows 环境)

遍历当前目录下所有txt文件提取年份:

Get-ChildItem -Filter *.txt | ForEach-Object {
    $_.Name -match '_(\d{4})\.[^.]+$' | Out-Null
    $matches[1]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 10:15:01