【问题标题】:How to save information in json file without deleting previous information python如何在json文件中保存信息而不删除以前的信息python
【发布时间】:2016-04-21 18:49:02
【问题描述】:

我正在使用 python 和 kivy 制作一个应用程序,允许用户为其葡萄糖读数创建一个新条目。现在它保存到 json 文件中,但另一个新条目删除了以前的数据。如何使每个条目分别保存,以便我可以访问用户历史记录的信息?

.py 文件

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.graphics import Color, Rectangle
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import AsyncImage
from kivy.uix.label import Label
from kivy.properties import StringProperty, ListProperty
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.textinput import TextInput
from kivy.network.urlrequest import UrlRequest
from kivy.storage.jsonstore import JsonStore
from os.path import join
from os.path import exists
from kivy.compat import iteritems
from kivy.storage import AbstractStore
from json import loads, dump
from kivy.config import Config
import os
import errno



class Phone(FloatLayout):
    def __init__(self, **kwargs):
        # make sure we aren't overriding any important functionality
        super(Phone, self).__init__(**kwargs)

    with self.canvas.before:
        Color(0, 1, 0, 1)  # green; colors range from 0-1 instead of 0-255
        self.rect = Rectangle(size=self.size, pos=self.pos)

    self.bind(size=self._update_rect, pos=self._update_rect)


    if not os.path.exists('hello.json'):
        with open('hello.json', 'wt') as inFile:
            inFile.write("")

    else:
        with open('hello.json') as inFile:
            try:
                data = Phone.load(self)
            except KeyError:
                data = []

def _update_rect(self, instance, value):
    self.rect.pos = instance.pos
    self.rect.size = instance.size

def product(self, instance):
    self.result.text = str(float(self.w.text) * 703/ (float(self.h.text) * float(self.h.text)))

def save(self):
    store = JsonStore('hello.json')
    name = self.n.text
    gender = self.g.text
    dtype = self.t.text
    height = self.h.text
    weight = self.w.text
    bmi = self.result.text
    medications = self.m.text
    insulin = self.ti.text
    store.put('profile', name=name, gender=gender, dtype=dtype, height=height, weight=weight, bmi=bmi, medications=medications, insulin=insulin)


def save_entry(self):
    time = self.gt.text
    glucose = self.gr.text
    carbs = self.c.text
    medications_taken = self.mt.text
    store.put('entry', time=time, glucose=glucose, carbs=carbs, medications_taken=medications_taken)



def load(self):
    store = JsonStore('hello.json')
    profile = store.get('profile')
    self.n.text = profile['name']
    self.g.text = profile['gender']
    self.t.text = profile['dtype']
    self.h.text = profile['height']
    self.w.text = profile['weight']
    self.result.text = profile['bmi']
    self.m.text = profile['medications']
    self.ti.text = profile['insulin']






presentation = Builder.load_file("main.kv")

class PhoneApp(App):
    def build(self):
        store = JsonStore('hello.json')

        return Phone()



if __name__ == '__main__':
    PhoneApp().run()

【问题讨论】:

  • 加载 json,解码为本机结构,对该结构进行必要的更改,然后重新编码为 json 并保存新副本。
  • @MarcB 如何解码为原生结构?

标签: android python json save kivy


【解决方案1】:

使用像this 这样的小型 json 数据库来保持它的整洁。示例用法:

from tinydb import TinyDB, Query

db = TinyDB('./db.json')
User = Query()
db.insert({'name': 'John', 'age': 22})
result = db.search(User.name == 'John')
print result

【讨论】:

  • @jilgeza 我以前从未使用过数据库,但您的示例使用的是您提供的数据,而不是来自用户的数据。理想情况下,我想将每个条目放在一个数组中并调用数组中的点来使用信息
  • @Azaro 这只是一个例子,按照文档来实现你的目标。代替用户 dict(姓名和年龄),将 dict 与您的数据放在一起,然后执行插入功能。
  • @jilgeza 我得到了它,它工作正常,但我怎么称呼说第一组条目?
  • @Azaro result 是一个列表。第一组(可能)是result[0],最后一组是result[-1]
  • @jilgeza 尝试此操作后,我得到 IndexError: index out of range 这与结果 [1] 相同
猜你喜欢
  • 2019-09-18
  • 2015-10-02
  • 1970-01-01
  • 2015-04-21
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
相关资源
最近更新 更多