0

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

Isa
  • 145
  • 8

1 Answers1

0

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) 
mgmussi
  • 520
  • 1
  • 4
  • 19
  • thank you, @mgmussi, I dare to ask one more thing, I'm trying to create a new df and save it as 'my_file' but for some reason is not copied into the excel file that I save it as 'my_file'. Meaning, the file is created but is empty, here is my code, do you see some issues with it? Actually, im pasting it into the initial description – Isa Sep 30 '20 at 17:48
  • not really but I managed to copy somehow creating another df :) still trying with the row because is not inserting above the columns but under. Anyway, thanks a lot for your help, will mark as the correct answer since the initial issue has been solved – Isa Sep 30 '20 at 19:42