kanwarprogrammer
kanwarprogrammer

Reputation: 53

How to Save DataFrame to Excel file using filedialog as SaveAs-Dialog in Python?

How can we write DataFrame object of Pandas using filedialog in Python TKinter?

file = filedialog.asksaveasfile(mode='w', defaultextension=".xlsx")
data.to_excel(file)

Whenever I try to write it it gives me error.

stat: path should be string, bytes, os.PathLike or integer, not _io.TextIOWrapper

I have been searching this error for hours, but the solutions are not working.

Upvotes: 3

Views: 2450

Answers (3)

Bending Rodriguez
Bending Rodriguez

Reputation: 701

I have stumbled across this old question because I had the task to create an excel out of a Dataframe with a SaveAs-Dialog. From my point of view both answers contain a partial solution but both are missing some aspect, therefore I provide my own:

First get the desired Path and Name of your File as a String by:

filePath = filedialog.asksaveasfilename(defaultextension='.xlsx')

Second, use the resulting Filepath with the Filename incorporated to create the Excel-File by calling to_excel on the respective Dataframe:

yourDataframe.to_excel(str(filePath))

Upvotes: 0

buran
buran

Reputation: 14233

use

file = filedialog.asksaveasfilename(defaultextension=".xlsx")

tkinter.filedialog.asksaveasfilename will return filename as string, not file object like tkinter.filedialog.asksaveasfile

Upvotes: 5

U13-Forward
U13-Forward

Reputation: 71580

You need to use str:

data.to_excel(str(file) + '.xlsx')

Upvotes: 0

Related Questions