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.


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

The below dialogue box opens to browse a file.

Then we choose a file.


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!
Published on 26-Feb-2020 07:34:28