首页 > 解决方案 > 使用 tk filedialog 以特定名称保存文件

问题描述

有没有办法使用 filedialog 将 DataFrame 保存到 excel 文件中,但是例如使用特定名称作为“my_file”?我通常使用此代码

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

这将打开一个窗口,我可以在其中选择文件的位置和名称,现在我希望默认名称为“my_file”,这样就不需要键入它了。

有没有办法做到这一点?非常感谢提前

保存的excel文件为空:

 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)

有没有可能像这张图片一样在列名的顶部插入一行?我在 pandas doc 中找不到任何关于此的内容 在此处输入图像描述

标签: pythonexceltkintersavefiledialog

解决方案


主要问题

尝试使用函数的参数,initialfile例如asksaveasfilename

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

评论问题

关于 DataFrame 空虚,是因为您没有为它分配任何东西。要添加值,您可以使用loc

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

您也可以使用 来执行此操作concat,但请确保您的数据框具有相同数量的列。

并在顶部添加一行,@edyvedy13 在这里找到了这个有趣的解决方案:

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

推荐阅读