Save file with a specific name using tk filedialog

598 views Asked by At

Is there a way to save a DataFrame into an excel file with filedialog but, using a specific name as 'my_file' for example? I usually use this code

path_to_save = filedialog.asksaveasfilename(defaultextension='.xlsx')
    df.to_excel(path_to_save, index=False)

and this opens a window where I can choose the location and name of my file just that, now I want to have the name 'my_file' by default so that typing it will not be necessary.

Is there a way of doing it?Many thanks in advance

The excel file saved is empty:

 a_row['column1'] = df['column1']
new_df = a_row
new_df2 = pd.DataFrame({'column2': [], '': []})
new_df3 = pd.concat([new_df, new_df2])
new_df3['column2'] = 'some value'
new_df3 = new_df3.set_index(['column1', 'column2'])

path_to_save1 = filedialog.asksaveasfilename(defaultextension='.xlsx',  initialfile = 'my_file')
new_df3.to_excel(path_to_save1, index=False)

Is there maybe away to insert a row on the top of columns name like in this image?I couldn't find anything in pandas doc about this enter image description here

1

There are 1 answers

2
mgmussi On BEST ANSWER

Main Question

Try using the parameter initialfile for the asksaveasfilename function, e.g.:

path_to_save = filedialog.asksaveasfilename(defaultextension='.xlsx', initialfile = 'my_file')

Comment Question

Regarding the DataFrame emptiness, is because you are not assigning anything to it. To add values, you can use loc:

df = pd.DataFrame({'column1':[],'column2':[]})
df.loc[0] = ['value1','value2']

You can also do that using concat, but make sure your dataframes have the same number of columns for that.

And to add a row on top, there was this interesting solution by @edyvedy13 found here:

df.loc[-1] = ['value1.0','value2.0']
df.insert(0,1,{'value2'})
df.index = df.index + 1
df.sort_index(inplace=True)