Reputation: 13
I am trying to download a CSV file in tkinter
by selecting location and filename to save CSV file generated from dataframe by using the code. But instead of saving file like this, I want to choose location using tkinter
to save my file.
data = {
'ans': list1, 'p': list2, 'td': list3
}
df = pd.DataFrame(data)
df.to_csv('filenotpath.csv', header=False, index=False)
df.to_csv(r'E:\fileHOpath.csv', index=False)
Upvotes: 1
Views: 931
Reputation: 143
First you can define a function that takes to two arguments with a dataframe (df) and a status from your tkinter entry (BooleanVar).
global save_status
save_status = False
def save_file(data, status):
global save_status
save_status = status
if save_status:
file_path = filedialog.asksaveasfilename(defaultextension=".csv",
filetypes=[("csv file", ".csv")],
)
data.to_csv(file_path, sep = ";", index = False, decimal = ",")
Then you can call this function after df = pd.DataFrame(data)
, as shown in my case below:
data = np.array([mvol, mcurr])
data = data.transpose()
data = pd.DataFrame(data, columns = ["Voltage [V]", "Current [A]"])
# save file using status
save_file(data, self.save.get())
Here, self.save.get()
is boolean value whose change depends on the status of checkbox as shown below:
self.save = tk.BooleanVar(value = False)
save = ttk.Checkbutton(self, text = "Save Data",
variable = self.save, onvalue = True, offvalue = False)
Upvotes: 0
Reputation: 46831
You can use tkinter.filedialog.asksaveasfilename()
to select the output file:
from tkinter.filedialog import asksaveasfilename
import pandas as pd
...
filename = asksaveasfilename(filetype=[('CSV files', '*.csv')])
if filename:
data = {'ans': list1, 'p': list2, 'td': list3}
df = pd.DataFrame(data)
#df.to_csv(filename, header=False, index=False)
df.to_csv(filename, index=False)
...
Upvotes: 1