简体   繁体   English

Android如果不存在python,如何创建一个新的json文件

[英]Android How to create a new json file if it doesn't exist python

I am creating an app that lets the user enter information and can save the data into a json file called hello.json. 我正在创建一个应用程序,让用户输入信息,并可以将数据保存到名为hello.json的json文件中。 This works fine when the file exists, however when testing it on an android it crashed because it does not contain this file. 这在文件存在时工作正常,但是当在android上测试时它崩溃了,因为它不包含这个文件。 How can I create a new json file on android if it doesn't exist? 如果它不存在,如何在android上创建一个新的json文件?

.py file .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 exists
from kivy.compat import iteritems
from kivy.storage import AbstractStore
from json import loads, dump
from kivy.config import Config



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)

    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 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']

    try:
        store.get('profile')['name']
    except KeyError:
        name = ""
    else:
        name = store.get('profile')['name']        




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

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

        return Phone()



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

You should use with open('hello.json', 'a+') as inFile 您应该使用with open('hello.json', 'a+') as inFile

a+ Opens a file for both appending and reading. a +打开文件以进行追加和阅读。 The file pointer is at the end of the file if the file exists. 如果文件存在,则文件指针位于文件的末尾。 The file opens in the append mode. 该文件以追加模式打开。 If the file does not exist, it creates a new file for reading and writing. 如果该文件不存在,则会创建一个用于读写的新文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android编程的新功能-如果不存在则创建数据库 - New on android programming - create a database If it doesn't exist 如果 Android Gradle Build 中不存在默认属性文件,我该如何创建它 - How can I create a default properties file if it doesn't exist in Android Gradle Build 如果Android目录尚不存在,如何自动创建 - How to create Android directory automatically if it doesn't already exist 读取文件(如果不存在),然后创建 - Read a file, if it doesn't exist then create Android:检查文件是否存在,是否不创建新文件 - Android: Check if file exist and if not create new one 如果文件夹不存在,则创建一个文件夹,然后创建一个文件并共享它 - Create a folder if it doesn't exist, then create a file and share it 如何从第一个活动 android studio 中不存在的第二个活动添加新数据? - How to add new data from second activity that doesn't exist in first activity android studio? Android Studio不会创建新项目 - Android Studio doesn't create new project Android如何在启动时创建数据库(如果该数据库不存在),然后在下一次启动时检索它 - Android How to create database on Startup if it doesn't exist and then retrieve it on next Startups Android 文件不存在(但同时存在!) - Android File Doesn't Exist (But does at the same time!)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM