我正在尝试记录每个循环中的数据值。我的问题是代码仅记录一项,而不是每 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/