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

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())
Tkinter Filedialog Treeview asksaveasfile() Upload and display image file

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