Python写入scenario_out.txt无报错但文件为空问题求助
问题根因
- Python内置的
print()函数默认输出到控制台,你虽然在函数入参里接收了待写入的文件对象file_object,但调用print()时没有指定file参数,所有内容都只输出到了终端,没有写入scenario_out.txt文件,所以最终生成的文件为空。
修复方法
直接修改代码中调用print()的部分,添加file=file_object参数即可,修改后的代码片段如下:
if save_to_file == True: print(' Year :' , scen_year, '\n Age :',age, '\n Start Bal :', (format(s_bal, ',.2f')) , '\n Start Bal PV :', (format(bal_pv, ',.2f')), '\n Invest Gains :', (format(inv_gains, ',.2f')), '\n Ann Savings :', (format(ann_savings,',.2f')), '\n SS Payment :', (format(ss_payment, ',.2f')), '\n Major Inc :', (format(major_inc, ',.2f')), '\n Major Exp :', (format(major_exp, ',.2f')), '\n Tax Rate :', (format(tax_rate, '.2%')), '\n Targ Ret Spend :', (format(tar_ret_spend, ',.2f')), '\n Net Ret Spend :', (format(net_ret_spend, ',.2f')), '\n Ret Pre-tax Spend :', (format(ret_pre_tax_spend, ',.2f')), '\n Taxes :', (format(taxes, ',.2f')), '\n End Bal :', (format(end_bal, ',.2f')), file=file_object)
额外优化建议
- 操作文件时优先使用
with上下文管理器,会自动完成文件关闭、缓冲区刷新操作,不需要手动调用close(),避免因忘记关闭文件导致的写入内容丢失问题,示例写法:
# 测试代码优化后写法 with open("scenario_out.txt","w") as out_file: file_save_flow(save_to_file = True, file_object = out_file, scen_year = 0, age = 60, s_bal = 100000, bal_pv = 100000, inv_gains = 1000, ann_savings = 1000, ss_payment = 1000, major_inc = 1000, major_exp = 1000, tax_rate = 0.15, tar_ret_spend = 50000, net_ret_spend = 40000, ret_pre_tax_spend = 60000, taxes = 10000, end_bal = 120000 ) with open("scenario_out.txt","r") as in_file: print(in_file.read())
内容的提问来源于stack exchange,提问作者Diesel
相关产品推荐
相关产品推荐

