如何简单地在JSON文件中添加一行。在代码的第一部分,将生成一个JSON文件。在while循环中,我只想输入代码,而不是在每个循环中都生成整个文档。 “数据”字符串每秒钟增长一次,因此使每个循环的生成新的JSON变得更加复杂。 自从我的BeagleBoneBlack运行该程序以来,我就在使用Python 2.7。
import json
from time import sleep
# Make it work for Python 2+3 and with Unicode
import io
try:
to_unicode = unicode
except NameError:
to_unicode = str
Val1=123
Val2=321
timesteps = 1
data = [{'Timestep': timesteps, 'Cur1': Val1, 'Cur2': Val2}]
# Write JSON file for Current
with io.open('data.json', 'w', encoding='utf8') as outfile:
str_ = json.dumps(data,
indent=4, sort_keys=True,
separators=(',', ': '), ensure_ascii=False)
outfile.write(to_unicode(str_))
#here the Loop starts
while True:
if timesteps < 50:
timesteps = timesteps + 1
Val1=123
Val2=321
data.insert(len(data), {'Timestep': timesteps, 'Cur1': Val1, 'Cur2': Val2})
# Write JSON file again
with io.open('Current.json', 'w', encoding='utf8') as outfile:
str_ = json.dumps(data,
indent=4, sort_keys=True,
separators=(',', ': '), ensure_ascii=False)
outfile.write(to_unicode(str_))
print "Entry successfull"
sleep(1)
else:
print "Time up!"
break
答案 0 :(得分:0)
我通过给出退出命令来解决此问题,该命令结束循环并仅将JSON保存一次。 在循环本身期间,仅获取数据,但不保存JSON。 如果你们想要整个代码,请告诉我。