askopenfile() function in Python Tkinter

PythonServer Side ProgrammingProgramming

Instead of hard coding the path to a file to be used by a python program, we can allow the user to browse the os folder structure using a GUI and let the user select the file. This is achieved using the tkinter module in which we define a canvas and put a button on it to browse the files.

In the below program, we define a file opener function. We only use this function to open a text file as python can read the content of a text file and print it out in a much readable manner. We can read any text based files like .txt or .csv files.

Example

from tkinter import *
from tkinter import filedialog
base = Tk()
# Create a canvas
base.geometry('150x150')
# Function for opening the file
def file_opener():
   input = filedialog.askopenfile(initialdir="/")
   print(input)
   for i in input:
      print(i)
# Button label
x = Button(base, text ='Select a .txt/.csv file', command = lambda:file_opener())
x.pack()
mainloop()

The below dialogue box opens to browse a file.

Then we choose a file.

Output

Running the above code gives us the following result −

<_io.TextIOWrapper name='C:/Users/Pradeep/Documents/welcome.txt' mode='r' encoding='cp1252'>
Hello There !
Welcome to Tutorialspoint!
raja
Published on 26-Feb-2020 07:34:28
Advertisements