簡體   English   中英

如何在 JSON 文件中重復保存 python output 值

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

嘿,伙計們,這可能是一個業余問題,但我如何不斷列出延遲值。 正如您在終端中看到的那樣,我有幾個值,但是每個新值都會覆蓋它們。 我如何在列表中打印所有新的 python output 值,例如

  1. {“延遲”:“計算時間為 0.039332 秒”}
  2. {“延遲”:“計算時間為 0.025932 秒”}
  3. {“延遲”:“計算時間為 0.032072 秒”}
  4. {"Latency": "0.049562s for the calculation"} 等等...而不是只有一個
  5. {"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) 

我的 python 代碼 + 終端 + Json 文件作為 linux 上的屏幕截圖

如果您使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM