python - 使用 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)
解决方案
主要问题
尝试使用函数的参数,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)
推荐阅读
- json - Postgresql:如何在关键 LIKE 的 JSON 中获取价值?
- apache-storm - Storm UI 数据 - 隐藏系统统计信息/显示系统统计信息
- java - 使用方法使用文件行输入制作字符串数组
- google-admin-sdk - 谷歌工作区 API 的访问被拒绝
- arrays - 为什么我无法在我的搜索函数中投射 void 指针?
- javascript - Three.js:Safari Mac 中没有出现的场景
- javascript - 如何清空由javascript填充的div标签
- json - 错误解析错误:Google 富测试结果中缺少“}”或对象成员名称
- react-native - 使用 firestore 时出现以下错误错误:FIRESTORE (8.1.2) INTERNAL ASSERTION FAILED: Unexpected state
- python - Python Data Frame Matplotlib - 绘制 x 轴时间格式问题