0

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:\Users\Hp\PycharmProjects\pythonProject\venv\Scripts\python.exe "C:\Users\Hp\PycharmProjects\pythonProject\open a file.py" File "C:\Users\Hp\PycharmProjects\pythonProject\open a file.py", line 7 file = open(filepath), 'r') ^ SyntaxError: unmatched ')'

Process finished with exit code 1

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hahaly
  • 23
  • 4
  • 5
    Typo: `open(str(filepath, 'r'))` => `open(str(filepath), 'r')`. Also, apparently `filepath` is an `_io.TextIOWrapper`, which can't be converted to a string. Looks like it's already a file you can call `read()` on. – ForceBru Oct 06 '22 at 11:36
  • `open(filepath), 'r')` should be `open(filepath, 'r')` ? – norok2 Oct 06 '22 at 11:54

2 Answers2

0

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()
ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

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()
Lachlan
  • 360
  • 5
  • 14