【问题标题】:How can i repeatedly save the python output values in a JSON file如何在 JSON 文件中重复保存 python 输出值
【发布时间】:2021-03-05 13:23:31
【问题描述】:

嘿,伙计们,这可能是一个非常业余的问题,但我如何不断列出延迟值。正如您在终端中看到的那样,我有几个值,但每个新值都会覆盖它们。如何在列表中打印所有新的 python 输出值,例如

  1. {"延迟": "0.039332s 用于计算"}
  2. {"延迟": "0.025932s 用于计算"}
  3. {“延迟”:“0.032072s 用于计算”}
  4. {“延迟”:“计算时间为 0.049562 秒”} 等等... 而不仅仅是一个
  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) 

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

【问题讨论】:

  • 请将您的代码以文本形式发布
  • 为了让我们帮助您,您必须展示您的努力并提交数据以用于重现您的问题。虽然提供图像很有帮助,但它不允许重现问题。请编辑您的问题以显示最小的可重现集。详情请见Minimal Reproducible Example
  • 所以,你想要的是追加到一个文件,而不仅仅是重写它。因此,以append 模式打开文件(例如open(fileName, 'a'))。然后,您可以相应地修改您的功能以添加序列号和东西。
  • @Alderven Mittal 我已经用我的代码编辑了这篇文章,任何帮助将不胜感激

标签: python json python-3.x list


【解决方案1】:

如果您使用w 模式打开文件,您将始终从文件开头开始写入。要附加到文件,请使用 a 模式打开文件,这将让您开始写入文件末尾:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-28
    • 2019-04-18
    • 2011-10-31
    • 2021-06-28
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多