1

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)
acw1668
  • 40,144
  • 5
  • 22
  • 34

2 Answers2

1

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)

...
acw1668
  • 40,144
  • 5
  • 22
  • 34
  • but now the problem is ,it is contiviously asking save file even after closing that window for many time ,and the data in exel file is filled only for two rows – SIDDHANT MESHRAM Dec 01 '21 at 09:08
  • My answer only shows that you can use `asksaveasfilename()` to select output file. As you didn't post a [mre], how can we know why you get the error? – acw1668 Dec 01 '21 at 09:10
0

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)
        
aVral
  • 65
  • 1
  • 9