python - 如何在 while 循环中记录数据值?

标签 python logging

我正在尝试记录每个循环中的数据值。我的问题是代码仅记录一项,而不是每 0.5 秒记录一次新的 TF 和 TC 值。我的相关代码是:

import time  
import math 
import os  
from time import strftime
import string
while True:
    Vmid = chan0.voltage
    Vthermistor = (Vsource - Vmid)
    Current = Vmid/Rfixed
    Rthermistor = Vthermistor / Current
    Ratio = Rthermistor / Rref
    print(' Vmid = %6.2f Vthermistor = %6.2f  Current = %8.4e' % (Vmid , Vthermistor, Current))
    X = math.log(Ratio)
    TK = 1/(A1 + B1*X + C1*X*X + D1*X*X*X)
    TC = TK - 273.15
    TF = TC * 1.8 + 32
    print(' Temperatures deg K %6.2f  deg C %6.2f   deg F %6.2f\n' % (TK, TC, TF))
    # hang out and do nothing for a half second
    log = open('log.txt', 'w') #open a text file for logging
    log.write('%s,%f,%f' % (strftime("%H:%M"), TF, TC)) #write to log
    time.sleep(0.5)

最佳答案

open() 模式从 w(写入,每次都会覆盖文件)更改为 a(追加)。

此外,一般来说,您想打开文件一次,因为写入后不会关闭它,因此在循环之前打开它,在循环中写入,在循环之后刷新并关闭它。

关于python - 如何在 while 循环中记录数据值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59954544/

相关文章:

python - 哪里可以找到docplex自动调优工具的文档?

python - 如何使用 pandas DataFrame.style?

python - ast.literal_eval 用于 python 中的变量?

java - 是否可以将 JBOSS AS 7 配置为使用 log4j 而不是其自己的日志框架?

python - 如何处理 sklearn GradientBoostingClassifier 中的分类变量?

python - 在 Python 中,元组是不可变对象(immutable对象)但允许包含列表的突变?

java - 从java连接到mongodb时如何防止登录控制台?

c# - 无法将跟踪事件记录到 Application Insights

logging - 自定义 NLog LogLevels 还是每个类有多个记录器?

Android 日志 dontpanic