在 Micropython 中以文本分隔符格式保存文件
Saving a file in a text delimiter format in Micropython
我想以文本分隔符的形式记录日期和温度,但使用尽可能少的消耗(即不使用 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", %d\n' % 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", %d\n' % val)
将导致文件 data.txt
包含类似以下数据的内容:
"2021-05-08 11:50:51", 319
"2021-05-08 11:50:52", 221
我想以文本分隔符的形式记录日期和温度,但使用尽可能少的消耗(即不使用 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", %d\n' % 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", %d\n' % val)
将导致文件 data.txt
包含类似以下数据的内容:
"2021-05-08 11:50:51", 319
"2021-05-08 11:50:52", 221