0

I am trying to create a program in python3 (Mac OS X) and tkinter. It takes an incremental id, the datetime.now and a third string as variables. For example,

a window opens displaying : id / date time / "hello world". The user makes a choice and presses a save button. The inputs are being serialised as json and saved in a file.

mytest = dict([('testId',testId), ('testDate',testDate), ('testStyle',testStyle)])
with open('data/test.txt', mode = 'a', encoding = 'utf-8') as myfile:
     json.dump(mytest, myfile, indent = 2)
myfile.close()

the result in the file is

{
  "testStyle": "blabla", 
  "testId": "8", 
  "testDate": "2013-05-09 13:32"
}{
  "testDate": "2013-05-09 13:41", 
  "testId": "9", 
  "testStyle": "blabla"
}

As a python newbie, I want to load the file data and make some checks, like "If user made another entry at 2013-05-09, display a message saying that you already entered data for today." What is the proper way to load all these json data ? The list will expand each day and will contain lots of data.

4

2 回答 2

1

您可以存储一个字典列表,而不是直接存储字典,该列表可以加载回一个可以修改和附加到的列表中

import json
mytest1 = dict([('testId','testId1'), ('testDate','testDate1'), ('testStyle','testStyle1')])
json_values = []
json_values.append(mytest1)
s = json.dumps(json_values)
print(s)
json_values = None
mytest2 = dict([('testId','testId2'), ('testDate','testDate2'), ('testStyle','testStyle2')])
json_values = json.loads(s)
json_values.append(mytest2)
s = json.dumps(json_values)
print(s)
于 2013-05-10T08:33:32.420 回答
1

您可以简单地加载文件并解析它:

with open(path, mode="r", encoding="utf-8") as myfile:
    data = json.loads(myfile.read())

现在你可以data随心所欲地做任何事情。

如果您的文件真的很大,那么我想您应该改用适当的数据库。

于 2013-05-10T08:37:31.703 回答