Skip to main content
 首页 » 编程设计

python之更新 txt 文件以检查 python 将数据保存到其中

2024年12月31日9bluestorm

在某些代码中,例如 MCMC,它会持续数小时甚至数天才能完成。 现在我想知道在 Python 运行时如何查看保存在 text file 中的输出。因为在我的代码中,只有在完成 Python 的工作后才能检查 txt 文件 中的全部输出

def ....(): 
   return 
def ....(): 
   return 
...... 
with open('outputs/p.txt', 'w') as f: 
 ..... 
   f.write("{0}\t{1}\n".format(A,B)) 

使用这段代码,我只能在完成 python 运行后才能看到输出。但如果我们每次都可以检查它,那将是有益的。

请您参考如下方法:

#the a+ appends the file at the end with your new data, or creates the file if it doesn't exist 
with open('outputs/p.txt', 'a+') as f: 
 
    f.write("{0}\t{1}\n".format(A,B)) 
 
    f.close()