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_w.title('www.plus2net.com')
my_font1=('times', 18, 'bold')
l1 = tk.Label(my_w,text='Upload File & read',width=30,font=my_font1)  
l1.grid(row=1,column=1)
b1 = tk.Button(my_w, text='Upload File', 
   width=20,command = lambda:upload_file())
b1.grid(row=2,column=1) 

def upload_file():
    file = filedialog.askopenfilename()
    fob=open(file,'r')
    print(fob.read())
    #file = filedialog.askopenfile()
    #print(file.read())
my_w.mainloop()  # Keep the window open
Output is here ( based on the uploaded file )
id,name,class,mark,gender
1,John Deo,Four,75,female
2,Max Ruin,Three,85,male
3,Arnold,Three,55,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 
        fob=open(file,'r')
        print(fob.read())
        #file = filedialog.askopenfile()
        #print(file.read())
    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(
        initialdir='D:\\my_data\\my_html\\',
        filetypes=[("CSV files", ".csv")])

title

file = filedialog.askopenfilename(
        initialdir='D:\\my_data\\my_html\\',
        title='Upload to plus2net',
        filetypes=[("CSV files", ".csv")])

filetypes

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

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' )
l2.grid(row=3,column=1) 
my_str.set("")
def upload_file():
    file = filedialog.askopenfilename()
    if(file):
        my_str.set(file)
        fob=open(file,'r')
        print(fob.read())
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)
    print(file)
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
    
    print(file.read())

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("www.plus2net.com")  #  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,
    command=lambda:my_fun(),bg='lightgreen')
b1.grid(row=0,column=0,padx=10,pady=20)

l1=tk.Label(my_w,text=my_dir,bg='yellow',font=18)
l1.grid(row=0,column=1,padx=2)
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


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    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-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer