[英]How can i repeatedly save the python output values in a JSON file
嘿,伙計們,這可能是一個業余問題,但我如何不斷列出延遲值。 正如您在終端中看到的那樣,我有幾個值,但是每個新值都會覆蓋它們。 我如何在列表中打印所有新的 python output 值,例如
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
模式打開文件,您將始終在文件開頭開始寫入。 將 append 寫入文件,以a
模式打開文件,這將讓您開始寫入文件末尾:
with open(filePathNameWExt, 'a') as fp:
# write to fp will not overwrite existing data
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.