How to write data of type DataFrame using asksaveasfile dialog

Question:

I am trying to save my data from an input csv file and write it to another csv file. I know how to write the dataFile using the to_csv method and using a pre-determined file to write into(output.csv). How do I do it via asksaveasfile dialog method. Any help is appreciated.

import csv
import pandas as pd
import os
import tkinter as tk
from tkinter import filedialog


SAVING_PATH = 'C:/Users/Desktop/'
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename() 
dataFile=pd.read_csv(file_path,usecols=['Name','Email','Gender'])
dataFile.to_csv(os.path.join(SAVING_PATH,r'output.csv'))
dataFile = filedialog.asksaveasfile(mode='w', defaultextension=".csv")
Asked By: Aurora_Titanium

||

Answers:

Nevermind I fixed the problem already.

import csv
    import pandas as pd
    import os
    import tkinter as tk
    from tkinter import filedialog

    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.askopenfilename() 
    dataFile=pd.read_csv(file_path,usecols=['Name','Email','Gender'])
    SAVING_PATH = filedialog.asksaveasfile(mode='w', defaultextension=".csv")
    dataFile.to_csv(SAVING_PATH)
Answered By: Aurora_Titanium

@Aurora_Titanium, it wokrs for me as well. But it creates an extra empty row after each row.

So I slightly modified yours:

data = pd.DataFrame(data, columns = ["Voltage [V]", "Current [A]"])
       
file_path = filedialog.asksaveasfilename(defaultextension=".csv",
                                            filetypes=[("csv file", ".csv")],
                                            )  
data.to_csv(file_path, sep = ";", index = False, decimal = ",")

Output:

     Voltage [V]  Current [A]
              1            1
              2            2
              3            3
              4            4
              5            5
              6            6
              7            7
              8            8
              9            9
             10           10
Answered By: Avral
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.