askopenfilename()
returns the path of the selected file or empty string if no file is selected:
from tkinter import filedialog as fd
filename = fd.askopenfilename()
print(len(filename))
To open the file selected with askopenfilename
, you can simply use normal Python constructs and functions, such as the open
function:
if filename:
with open(filename) as file:
return file.read()
I think you are using askopenfile
, which opens the file selected and returns a _io.TextIOWrapper
object or None
if you press the cancel button.
If you want to stick with askopenfile
to get the file path of the file just opened, you can simply access the property called name
of the _io.TextIOWrapper
object returned:
file = fd.askopenfile()
if file:
print(file.name)
If you want to know more about all the functions defined under the filedialog
(or tkFileDialog
for Python 2) module, you can read this article.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…