RegEx match string to variable

Hi all,

Building a tool using tkinter to select file\path and stuff it into a variable to use in a function, but the str given by askopenfile() includes a lot of extra text in its return:

C:\Python\Python39\python.exe C:/shsscr/tools/iptoname/
<_io.TextIOWrapper name='C:/Users/name/Documents/test.csv' mode='r' encoding='cp1252'>

Process finished with exit code 0

I thought, OK, RegEx to the rescue , using regEx101 (favorite RegEx site), choose Python editor and worked out the following:


In Regex101 testor this pulled out ‘C:/Users/name/Documents/test.csv’ as a match

When using python “re” I get “<re.Match object; span=(0, 1), match=’<’>” instead of the file dialog matched string

import re
import tkinter
from tkinter import filedialog

p = re.compile(r'(.*?[^\\])')
tkinter.Tk().withdraw()  # stops empty tkinter window

folder_path = filedialog.askopenfile()

file_path = p.match(str(folder_path))

Tried group match, but with only 2 groups, niether pulled the string match, what am I doing wrong.

Yes, this is my first time trying RegEx in Python …

Thanks in advance …

The return value of askopenfile() isn’t a string, it’s actually a file object opened for you. To get the filename, you can just use askopenfilename() instead.

Thanks for the comment , pointed me in the right direction, got to get use to checking the docs on first use of a function I’ve never used before.

Clearly shows the difference if you read them … my fault, again, thanks.