How is it an unmatched ")"?

Question:

Consider:

from tkinter import *
from tkinter import filedialog


def openFile():
    filepath = filedialog.askopenfile()
    file = open(filepath), 'r')
    print(file.read())
    file.close()



window = Tk()

button = Button(text="Open",command=openFile)
button.pack()

window.mainloop()

Error:

C:UsersHpPycharmProjectspythonProjectvenvScriptspython.exe "C:UsersHpPycharmProjectspythonProjectopen a file.py"
File "C:UsersHpPycharmProjectspythonProjectopen a file.py", line 7
file = open(filepath), ‘r’)
^
SyntaxError: unmatched ‘)’

Process finished with exit code 1

Asked By: hahaly

||

Answers:

From the documentation of tkinter.filedialog.askopenfile:

…create an Open dialog and return the opened file object(s) in read-only mode.

So what filedialog.askopenfile() returns isn’t a file path (you’d use askopenfilename for that), but the file object you can read from:

def openFile():
    file = filedialog.askopenfile()
    print(file.read())
    file.close()
Answered By: ForceBru

The unmatched ')' comes from this line in your code which does have an unmatched ).

file = open(filepath), 'r')

You can access the filename string by adding .name to your filepath variable (and the fix for the unmatched ))

from tkinter import *
from tkinter import filedialog


def openFile():
    filepath = filedialog.askopenfile()
    file = open(filepath.name, 'r')
    print(file.read())
    file.close()



window = Tk()

button = Button(text="Open",command=openFile)
button.pack()

window.mainloop()
Answered By: Lachlan