我想用文本分隔符样式记录日期和温度,但要尽可能减少消耗(即不使用任何库,如CSV或Pandas(。
到目前为止,我已经尝试过了:
while hours < 2:
hours += 1
text = "%4d-%02d-%02d %02d:%02d:%02d" % utime.localtime()[:6], get_temp()
row.append(text)
utime.sleep(1)
输入这个:
[('2021-05-08 16:05:44', 347), ('2021-05-08 16:05:45', 344)]
然而,我希望数据以这种格式存储:
"2021-05-08 16:05:44", 22
"2021-05-08 16:05:45", 19
...
编写时:
text = "%4d-%02d-%02d %02d:%02d:%02d" % utime.localtime()[:6], get_temp()
您将变量text
设置为元组((x, y)
值(,而不是字符串。如果您想以所显示的格式输出行,您可以执行以下操作:
with open('output.txt', 'a') as fd:
fd.write('"%s", %dn' % text)
例如,以下代码:
import time as utime
import random
def get_temp():
return random.randint(100, 400)
hours = 0
row = []
while hours < 2:
hours += 1
text = "%4d-%02d-%02d %02d:%02d:%02d" % utime.localtime()[:6], get_temp()
row.append(text)
utime.sleep(1)
with open('data.txt', 'a') as fd:
for val in row:
fd.write('"%s", %dn' % val)
将导致文件data.txt
包含类似以下数据的内容:
"2021-05-08 11:50:51", 319
"2021-05-08 11:50:52", 221