Get file path from Tkinter filedialog not working

Question:

Working on a project where I have a function that shows an open file dialog and prints out the path to the selected file.

My code looks like this:

import tkinter
import customtkinter

def openFile(self):
        filePath = tkinter.filedialog.askopenfile(initialdir=startingDir, title="Open File", filetypes=(("Open a .txt file", "*.txt"), ("All files", "*.*")))
        if filePath == '':
            tkinter.messagebox.showwarning("Warning", "You didn't select a file.")
        else:
            print(filePath)

However, I received this error from Visual Studio Code:

Argument of type "IO[Incomplete] | None" cannot be assigned to parameter "file" of type "_OpenFile" in function "open"

And this one from Python itself:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:UsersbenriAppDataLocalProgramsPythonPython310libtkinter__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:UsersbenriAppDataLocalProgramsPythonPython310libsite-packagescustomtkinterwidgetsctk_button.py", line 377, in clicked
    self.command()
  File "C:UsersbenriOneDriveDesktopMy FilesApps and ProgramsWindows ProgramsPythonTexTypeeditFile.py", line 51, in openFile
    mainFile = open(filePath, "r")
TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper

UPDATE:

If I use the syntax mainFile = open(str(filePath), "r"), Python gives me the following error:

FileNotFoundError: [Errno 2] No such file or directory: ‘PY_VAR0’

suggesting that this method of using str() results in a variable with invalid contents.

Asked By: Ben the Coder

||

Answers:

askopenfile returns a file handle, not a file name. Whatever file you pick is automatically opened and the handle is returned.

You can’t pass a file handle to open. If you want the file name, use askopenfilename instead of askopenfile. Or, just use the already open file that askopenfile returns.

Answered By: Bryan Oakley