简体   繁体   中英

How can i repeatedly save the python output values in a JSON file

Hey guys this is probably such an amateur question to ask but how do i constantly list the latency value. As you can see in the Terminal i have several values but they get overwritten for each new value. how do i print all of the new python output values in a list like for example

  1. {"Latency": "0.039332s for the calculation"}
  2. {"Latency": "0.025932s for the calculation"}
  3. {"Latency": "0.032072s for the calculation"}
  4. {"Latency": "0.049562s for the calculation"} and so on... instead of just one
  5. {"Latency": "0.039332s for the calculation"} which gets overwritten with each new value
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) 

My python code + Terminal + Json file as a screenshot on linux

If you open a file with the w mode, you will always start writing to it at the beginning of the file. To append to a file, open the file with the a mode, this will let you start writing to the end of the file instead:

with open(filePathNameWExt, 'a') as fp:
    # write to fp will not overwrite existing data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM