I'm 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:
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 an 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 IDLE:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\benri\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\benri\AppData\Local\Programs\Python\Python310\lib\site-packages\customtkinter\widgets\ctk_button.py", line 377, in clicked
self.command()
File "C:\Users\benri\OneDrive\Desktop\My Files\Apps and Programs\Windows Programs\Python\TexType\editFile.py", line 51, in openFile
mainFile = open(filePath, "r")
TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper
Can someone tell me the issue and how to fix it? Thanks, Ben
EDIT:
Just discovered that 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.
CodePudding user response:
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.