Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save a csv file using asksaveasfilename in tkinter? [closed]

Tags:

python

tkinter

I'm trying to create a tkinter application where we are supposed to have an entry that can be used to save a csv file using the filedialog.asksaveasfilename module.

So far what I achieved shown below, but it needs to be improved. Please help.

import matplotlib.pyplot as plt
import numpy as np
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import pandas as pd

win = tk.Tk()
win.title('Save')
win.geometry('200x150')


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 = ",")

    # wigets
    save_var = tk.BooleanVar(value = False) 
    save_check= ttk.Checkbutton(win, text = "Save Data", 
                 variable = save_var, onvalue = True, offvalue = False, width = 10)
    save_check.pack(side = "left", padx = 15, pady = 10)
    
    #  data 
    df = pd.DataFrame({"Age": [23, 35, 75], 
                      "Salary": [2000, 2500, 4000]})

    # save file according to status of checkbox
    save_file(df, save_var.get())

    win.mainloop()

Output shown in graph below.

enter image description here

like image 822
sandyspace Avatar asked Dec 07 '25 06:12

sandyspace


1 Answers

You can do this to ask for file name:

asksaveasfilename(filetypes = [('All tyes(*.*)', '*.*'),("csv file(*.csv)","*.csv")], defaultextension = [('All tyes(*.*)', '*.*'),("csv file(*.csv)","*.csv")])

You can open it when button is clicked by doing this:

from tkinter.filedialog import asksaveasfile
from tkinter import *

base = Tk()

def SaveFile():
   data = [('All tyes(*.*)', '*.*'),("csv file(*.csv)","*.csv")]
   file = asksaveasfilename(filetypes = data, defaultextension = data)
   # file will have file name provided by user.
   # Now we can use this file name to save file.
   with open(file,"w") as f:
      f.write(<data you want to save>)

save_btn = Button(base, text = 'Click to save file ', command = SaveFile)
save_btn.pack(side = TOP, pady = 20,padx = 50)

base.mainloop()

In filetypes and defaultextension you have to provide list of tuple, inside tuple you first element should be what user see and second element is the actual extension.

For more/detail information you can read documentation.

Twist: Actually you may use csv module itself, if you are trying to save csv files. There are other libraries also but it is straightforward and easy to use so, I am suggesting it. Here's the basic example:

import csv
with open('<file name.csv>', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
like image 186
imxitiz Avatar answered Dec 08 '25 21:12

imxitiz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!