Python Tkinter filedialog using askopenfile()

filedialog.askopenfile create a modal, native look-and-feel dialog for user to select and upload file from local system. .
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import askopenfile
File Upload Browser
Displaying file browser to upload read file path in Tkinter window using filedialog askopenfilename
Here is the code to open one file browser dialog box and then select a file to upload. After uploading the content of the file will be displayed in the console. Here only .csv file is uploaded.
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from tkinter.filedialog import askopenfile
my_w = tk.Tk()
my_w.geometry("400x300")  # Size of the window 
my_font1=('times', 18, 'bold')
l1 = tk.Label(my_w,text='Upload File & read',width=30,font=my_font1)  
b1 = tk.Button(my_w, text='Upload File', 
   width=20,command = lambda:upload_file())

def upload_file():
    file = filedialog.askopenfilename()
    #file = filedialog.askopenfile()
my_w.mainloop()  # Keep the window open
Output is here ( based on the uploaded file )
1,John Deo,Four,75,female
2,Max Ruin,Three,85,male
4,Krish Star,Four,60,female
5,John Mike,Four,60,female

When user cancels the file window

After opening the file browser the user may use the cancel button to close the operation, to handle this we have added the if file: in above code. The else part of the code will display the message.
def upload_file():
    file = filedialog.askopenfilename()
    if file: # user selected one file 
        #file = filedialog.askopenfile()
    else: # user cancel the file browser window
        print("No file chosen") 

options : initialdir

We can set the initial directory to be show to user.
file = filedialog.askopenfilename(
        filetypes=[("CSV files", ".csv")])


file = filedialog.askopenfilename(
        title='Upload to plus2net',
        filetypes=[("CSV files", ".csv")])


    f_types = [('All Files', '*.*'), 
             ('Python Files', '*.py'),
             ('Text Document', '*.txt'),
              ('CSV files',"*.csv")]
    file = filedialog.askopenfilename(

displaying the file path

We can use one Label with a StringVar() to display the path with name of the selected file.
Display path and name of uploaded file
my_str = tk.StringVar()
l2 = tk.Label(my_w,textvariable=my_str,fg='red' )
def upload_file():
    file = filedialog.askopenfilename()
my_w.mainloop()  # Keep the window open
Browse and select Excel file to create Pandas DataFrame

Selecting multiple files

By using the option multiple=True user can select multiple files and the output will contain one tuple with all file names ( with path ) .
file = filedialog.askopenfilename(multiple=True)
Output is here
('D:/my_data/mumbai1.xls', 'D:/my_data/mumbai2.xlsx', 'D:/my_data/my_data.csv')
From this tuple we can use the elements inside our script.
Mulitple image read & display using askopenfilename

difference between askopenfile() and askopenfilename()

The function askopenfilename() returns the selected file name. ( path as string ).
The function askopenfile() returns the opened file object in read mode.
In above code both can be used and watch the commented part of the code below for comparison of both functions. In both cases output is same.
def upload_file():
    #file = filedialog.askopenfile() # returns file object
    file = filedialog.askopenfilename() # returns path as string
    file=open(file,'r') # file object is created

Selecting directory

aksdirectory() to select folder
We can use askdirectory() to select any directory in your system as string. Here we are opening one dialog box to browse and select a folder. On selection of the folder, path will be displayed on a Label. User can change the selection also.

Tkinter filedialog askdirectory() to show dialog window to select directory & return path as string
import tkinter as tk
from tkinter import filedialog
my_w = tk.Tk()
my_w.geometry("400x200")  # Size of the window 
my_w.title("")  #  title
my_dir='' # string to hold directory path 
def my_fun(): 
    my_dir = filedialog.askdirectory() # select directory 
    l1.config(text=my_dir) # update the text of Label with directory path

b1=tk.Button(my_w,text='Select directory',font=22,

my_w.mainloop()  # Keep the window open
Tkinter Show directory and file structure in Treeview Filedialog show data in Treeview asksaveasfile() Upload and display image file
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2023 All rights reserved worldwide Privacy Policy Disclaimer