简体   繁体   中英

Permission denied to .json file when using a JSON file as a store in Kivy app

I'm trying to store a value in a JsonStore file but get the following error when button is clicked;

File "C:\\utils\\kivy\\kivy\\kivy\\storage\\jsonstore.py", line 39, in store_sync with open(self.filename, 'w') as fd: PermissionError: [Errno 13] Permission denied: 'storage.json'

# import Kivy
import kivy
import random
import json

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.storage.jsonstore import JsonStore

# my app
class MyApp(App):
# layout
    def build(self):
    # basic layout
        layout = BoxLayout(padding=10, orientation='vertical')
        self.store = JsonStore('storage.json')
        # widgets
        # button 1
        self.btn1 = Button(text="OK")
        self.btn1.bind(on_press=self.buttonClicked)
        layout.add_widget(self.btn1)
        # label 1
        self.lbl1 = Label(text="test")
        layout.add_widget(self.lbl1)
        # input 1
        self.txt1 = TextInput(text='', multiline=False)
        layout.add_widget(self.txt1)
        # return layout
        return layout




    # button click function
    def buttonClicked(self,btn):
        self.lbl1.text = "You wrote " + self.txt1.text
        self.store.put('myStorage1', value1=self.txt1.text, value2='test')
# run app
if __name__ == "__main__":
    MyApp().run()

Use Kivy's user_data_dir to automatically determine where user data is stored on different devices, then pass the full path of the file to store.

from kivy.storage.jsonstore import JsonStore
from os.path import join

data_dir = App().user_data_dir
store = JsonStore(join(data_dir, 'storage.json'))

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