Pandas variable path

Question:

I’m writing in python a simple excel into folder software using tkinter and pandas.
The first step of this program will be the file choice so I wrote:

data_path=StringVar()

def getPath():
    file = filedialog.askopenfile(mode='r', initialdir='/',
            filetypes=[("xlsx files", "*.xlsx")])
if file:
    filepath=os.path.abspath(file.name)
    data_path.set(filepath)
    Label(root, textvariable=data_path).grid(row=1,column=0,sticky='w', padx=100)
    
labels1_1 = Label (root, text = "Carica un File", 
                    font=('Arial', 12, 'bold')).grid(row=0,column=0,padx=5,sticky='w')

open_button = Button (root, text="Scegli un File", 
                    command=getPath).grid(row=1,column=0, padx=13, pady=5,sticky='w')

But if I set "data_path" as string and than I put into:

df = pd.read_excel(data_path)

It doesn’t work.
So how can I read the dataframe from user’s excel file?

Asked By: Matteo Petrillo

||

Answers:

data_path is an instance of StringVar, what you need is to get the value of it, so you have to use get() method to get its value:

df = pd.read_excel(data_path.get())

Furthermore, you don’t need askopenfile, you can just use askopenfilename which will return the absolute path of the file.

def getPath():
    file = filedialog.askopenfilename(initialdir='/',
            filetypes=[("xlsx files", "*.xlsx")])
    if file:
        data_path.set(file)
        Label(root, textvariable=data_path).grid(row=1,column=0,sticky='w', padx=100)
Answered By: Delrius Euphoria