python - 如何在 JSON 文件中重复保存 python 输出值
问题描述
嘿,伙计们,这可能是一个业余问题,但我如何不断列出延迟值。正如您在终端中看到的那样,我有几个值,但是每个新值都会覆盖它们。我如何在列表中打印所有新的 python 输出值,例如
- {“延迟”:“计算时间为 0.039332 秒”}
- {“延迟”:“计算时间为 0.025932 秒”}
- {“延迟”:“计算时间为 0.032072 秒”}
- {"Latency": "0.049562s for the calculation"} 等等...而不是只有一个
- {"Latency": "0.039332s for the calculation"} 被每个新值覆盖
from time import sleep
import datetime
import pymongo
import time
import json
# This URL provides connection to the database
uri = blahblah
# initialising pymongo client
client = pymongo.MongoClient(uri)
# Database where the records will be saved - reference to the database
db = client.Kostenanalyse
# Accessing the collection "latenz" from the Database
coll = db.latenz
#Defining the Start time
start_time = datetime.datetime.now()
start_time = datetime.datetime.now().isoformat()
end = time.perf_counter()
# Opens a file to read current temperature
with open(r"/sys/class/thermal/thermal_zone0/temp") as File:
ActualTemp = int(File.readline())/float(1000)
def create_info_data()-> dict:
return {
"CurrentTemp in °C" : ActualTemp,
"Time when packet was sent" : datetime.datetime.now().isoformat(),
"Sensor reading" : "",
"Latency" : end,
}
def writeToJSONFile(path, fileName, data):
filePathNameWExt = './' + path + '/' + fileName + '.json'
with open(filePathNameWExt, 'w') as fp:
json.dump(data, fp)
#While loop
while True:
data = create_info_data()
start = time.perf_counter()
coll.insert_one(data)
end = time.perf_counter() - start
print('{:.6f}s for the calculation'.format(end))
data = {}
data['Latency'] = '{:.6f}s for the calculation'.format(end)
writeToJSONFile('./','latency',data)
print(str(start_time) + str(float(ActualTemp)) + 'Wrote data sample {} to collpipection {}'.format(data, 'info'))
sleep(0.5)
解决方案
如果您使用该w
模式打开文件,您将始终在文件开头开始写入。要附加到文件,请使用a
模式打开文件,这将让您开始写入文件末尾:
with open(filePathNameWExt, 'a') as fp:
# write to fp will not overwrite existing data
推荐阅读
- angular - chrome 检查器显示错误定位的元素与 recaptcha
- c++ - 在cpp中除以大数时查找大二进制字符串的余数
- visual-studio - 如何防止其他 Visual Studio Online 团队成员重新分配任务?
- android - 使用 aapt 构建新的 Android App Bundle 失败
- node.js - Heroku 使用 Git Node.js 部署 multer 上传文件夹 检查文件
- nem - 多重签名钱包未转换。为什么聚合交易不返回错误?
- sas - 寻找最相似的短语
- python - 无法使用 Google Cloud 身份验证代替邮件设置
- java - 删除 oneToOne 后 Spring Hibernate TransientPropertyValueException
- java - 自动连接当前的 RememberMeServices