Python 3.7下使用Regex提取指定路径中.sav文件名的求助
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.savat the very end of the string (the$anchors it to the end)- The parentheses capture just the filename we want
Option 2: Use Python's Built-in Path Tools (Recommended!)
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

