数据没有打印到文件中,导致文件为空

Data does not print into the file, resulting in a empty file

我一直在尝试将此数据写入“scenario_out.txt”文件。然而,当我 运行 代码时,我没有得到任何错误,但我的文本文件确实变空了,所以没有数据被放入文件中。 .我正在复习我的笔记,但我没有看到哪里做错了。

 # Display results of scenario
    def file_save_flow(save_to_file,          # save to a file object if save_to_file = True
                       file_object,           # name of file object to save to
                       scen_year,
                       age,
                       s_bal,
                       bal_pv,
                       inv_gains,
                       ann_savings,
                       ss_payment,
                       major_inc,
                       major_exp,
                       tax_rate,
                       tar_ret_spend,
                       net_ret_spend,
                       ret_pre_tax_spend,
                       taxes,
                       end_bal
                       ):
        """ file_save_flow() test output
            >>> out_file = open("scenario_out.txt","w")
            >>> 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
            ...             )
            >>> out_file.close()
            >>> in_file = open("scenario_out.txt","r")
            >>> print(in_file.read())
            Year             :0
            Age              :60
            Start Bal        :100,000.00
            Start Bal PV     :100,000.00
            Invest Gains     :1,000.00
            Ann Savings      :1,000.00
            SS Payment       :1,000.00
            Major Inc        :1,000.00
            Major Exp        :1,000.00
            Tax Rate         :15.00%
            Targ Ret Spend   :50,000.00
            Net Ret Spend    :40,000.00
            Ret Pre-tax Spend:60,000.00
            Taxes            :10,000.00
            End Bal          :120,000.00
            <BLANKLINE>
            >>> in_file.close()
        
        """
    
        #=============================My Code================================
        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')))
      #============================================================================      
            
            
    
    # test function
    out_file = open("scenario_out.txt","w")    # set up the file object to write to
    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
                   )
    out_file.close()
    in_file = open("scenario_out.txt","r")     # read back the contents saved to the file
    print(in_file.read())
    in_file.close()

我绑定了一些 bool 变量用作标志,但仍然没有成功。

如果你去掉所有的绒毛,你的代码看起来就像这样:

def file_save_flow(save_to_file, file_object, data):
    if save_to_file == True:
        print('Data: ', data)

out_file = open("scenario_out.txt", "w")
file_save_flow(save_to_file=True, file_object=out_file, data='data')
out_file.close()
in_file = open("scenario_out.txt", "r")
print(in_file.read())
in_file.close()

由此,很明显您的函数只做一件事:如果 save_to_fileTrue,它会打印一些东西,否则什么也不打印。它对 file_object.

没有任何作用

因此,尽管您创建并打开了一个文件并将文件句柄传递给您的函数,但您实际上并没有在 print() 语句中使用它。

这可行:

def file_save_flow(save_to_file, file_object, data):
    if save_to_file == True:
        print('Data: ', data, file=file_object)
    else:
        print('Data: ', data)

或者,为了避免重复自己:

def file_save_flow(save_to_file, file_object, data):
    print('Data: ', data, file=file_object if save_to_file else None)

目前,您只是将输出打印到控制台,而不是实际将其保存到文件中。

你可能想要这样的东西

if save_to_file == True:
    output = (
          ' Year              : ' + str(scen_year) + 
        '\n Age               : ' + str(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_object.write(output)

这会创建一个大的输出数据字符串,然后将其写入文件对象。