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

Python 3.7下使用Regex提取指定路径中.sav文件名的求助

Fixing Your Filename Extraction Issue

Hey there! Let's break down why your current regex isn't working and get you the right filename easily.

What's Wrong With Your Current Regex?

Your pattern r'\\(.+).sav' uses greedy matching with .+, which means it will grab everything starting from the first backslash (\) in your path all the way up to the last .sav — that's why you're getting a huge chunk instead of just the final filename.

Option 1: Fix the Regex

If you still want to use regex, adjust the pattern to target only the content after the last backslash:

import re
txt = r'C:\Users...\Standard Loadflows Seq and Dyn PSSEv34 - 2019-02-20\AutumnHi-20180531-183047-34-SystemNormal\AutumnHi-20180531-183047-34-SystemNormal.sav'
result = re.findall(r'\\([^\\]+)\.sav$', txt)
print(result[0])  # Outputs: AutumnHi-20180531-183047-34-SystemNormal.sav

Let's break this down:

  • [^\\]+: Matches one or more characters that are not backslashes (so it stops at the last backslash)
  • \.sav$: Ensures we're matching the .sav at the very end of the string (the $ anchors it to the end)
  • The parentheses capture just the filename we want

Regex is overkill for path handling — Python has standard libraries that handle all edge cases (like different OS path separators, trailing slashes, etc.) automatically.

Using os.path (works in all Python 3 versions):

import os
txt = r'C:\Users...\Standard Loadflows Seq and Dyn PSSEv34 - 2019-02-20\AutumnHi-20180531-183047-34-SystemNormal\AutumnHi-20180531-183047-34-SystemNormal.sav'
filename = os.path.basename(txt)
print(filename)  # Outputs the exact filename you need

Using pathlib (modern, object-oriented approach for Python 3.4+):

Since you're using Python 3.7, pathlib is a great choice:

from pathlib import Path
txt = r'C:\Users...\Standard Loadflows Seq and Dyn PSSEv34 - 2019-02-20\AutumnHi-20180531-183047-34-SystemNormal\AutumnHi-20180531-183047-34-SystemNormal.sav'
filename = Path(txt).name
print(filename)

Both of these methods will reliably give you the final filename without having to mess with regex patterns.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:37:17