Get file path from askopenfilename function in Tkinter

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.

Leave a Comment