Python Excel导出GUI程序异常:CSV/TXT文件无法生成
修复Excel转CSV/TXT导出失败的问题
你已经定位到了问题核心:elif判断条件错误使用了export_path而非export_format。export_path是包含完整路径的文件名(比如D:/test/data.csv),永远不可能等于'csv'或'txt',所以CSV和TXT的导出分支完全不会执行,只有JSON分支因为用对了export_format能正常运行。
修复后的完整代码
def export(self): # Export data if self.filepath: try: df = pd.read_excel(self.filepath) export_format = self.file_choice.get() export_path = os.path.normpath(os.path.join(os.path.dirname(self.filepath), os.path.splitext(os.path.basename(self.filepath))[0] + '.' + export_format)) print(f"Exporting to: {export_path}") if export_format == 'json': df.to_json(export_path, orient='records', lines=True) elif export_format == 'csv': df.to_csv(export_path, index=False) elif export_format == 'txt': df.to_csv(export_path, index=False, sep='\t', header=True) self.label_file_explorer.configure(text=f"File exported to: {export_path}") self.label_file_explorer.place(x=110, y=350) except Exception as e: self.label_file_explorer.configure(text=f"Error: {e}") self.label_file_explorer.place(x=110, y=350) else: self.label_file_explorer.configure(text="No file selected.") self.label_file_explorer.place(x=110, y=350)
关键修改点
- 将两个
elif条件中的export_path替换为export_format,确保判断的是用户选择的导出格式后缀,而非完整文件路径。
修改后,CSV和TXT格式的导出分支会正常触发,生成对应的文件。
内容的提问来源于stack exchange,提问作者Trần Khôi
相关产品推荐
相关产品推荐

