- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
askopenfile() function in Python Tkinter
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!
Advertisements