I am trying to make a application to get a user to press a button and be able to open a csv file and then make a copy of that file in a certain directory, however the first line of code in the function won't work. Here is an excerpt of the code below.
import os
import pandas as pd
from tkinter import filedialog
import ttkbootstrap as tb
root = tb.Window(themename='superhero')
def add_spreadsheet():
spreadsheet_filepath = filedialog.askopenfilename(initialdir='C:\Users\peter\Downloads',
title='Select A File', filetypes=
('csv files', '*.csv'))
file_name = os.path.basename(spreadsheet_filepath)
df = pd.read_csv(spreadsheet_filepath)
output_path = os.path.join('csv files/', f'{file_name}')
df.to_csv(output_path, index=False)
# create add button to add a spreadsheet to a file
home_add_btn = tb.Button(root, text='Add', command=add_spreadsheet)
home_add_btn.pack(anchor='center', pady=10)
root.mainloop()
I tried online but I couldn't understand anything.
There are two things you have to improve:
r
or R
in front of the path name.Other options for path names, but in my opion the raw string is prefered.
filetypes
, because they are defined as a sequence of tuples, see doc.spreadsheet_filepath = filedialog.askopenfilename(initialdir= r'C:\Users\peter\Downloads', title='Select A File', defaultextension=".csv", filetypes=[("CSV Files", "*.csv")])
Here is a dummy code what opens the file dialoge:
from tkinter import *
from tkinter import filedialog
root = Tk()
def add_spreadsheet():
spreadsheet_filepath = filedialog.askopenfilename(initialdir= r'C:\Users',
title='Select A File', filetypes=
[('csv files', '*.csv')])
file_name = os.path.basename(spreadsheet_filepath)
df = pd.read_csv(spreadsheet_filepath)
output_path = os.path.join('csv files/', f'{file_name}')
df.to_csv(output_path, index=False)
# create add button to add a spreadsheet to a file
home_add_btn = Button(root, text='Add', command=add_spreadsheet)
home_add_btn.pack(anchor='center', pady=10)
root.mainloop()