0

我创建了一个字典并使用 json 将其保存到一个文件中。该代码需要输入并定期更新字典,但不幸的是我无法正确编写字典。以下是我编写的代码。看看这里:

import os, sys, pickle, re, json
from optparse import OptionParser

parser = OptionParser("Store Daily Intakes \n python [Options] <-h help>")
parser.add_option("-n", "--ndays", dest="ndays", action="store", type="int", help="Input the day")
parser.add_option("-m", "--morning", dest="morning", action="store", type="string", help="Input the morning intake format <Banana-1pc,Bread-1pc,CottageChees-2tbs>")
parser.add_option("-l", "--lunch", dest="lunch", action="store", type="string", help="Input the Lunch intake format <Rice-2tbs,Roti-1pc,ChickenCurry-2tbs,Dal-2tbs>")
parser.add_option("-a", "--afternoon", dest="afternoon", action="store", type="string", help="Input the afternoon intake format <Cornflakes-2tbs,Banana-1pc>")
parser.add_option("-d", "--dinner", dest="dinner", action="store", type="string", help="Input the dinner intake format <Pasta-20gms, Cheese-2slice>")

(options, args) = parser.parse_args()

if options.ndays is None or options.morning is None or options.lunch is None or options.afternoon is None or options.dinner is None :
   print parser.print_help()
   exit(-1)


if os.path.isfile("./DailyInTakeFile.json") is True :

    jout = file('./DailyInTakeFile.json','r') # read mode
    CurDct = json.load(jout)
    print CurDct

    DailyInTake = dict()
    DailyInTake["%d" % options.ndays] = {}
    din = DailyInTake["%s" % options.ndays]
    din['Morning'] = options.morning
    din['Lunch'] = options.lunch
    din['Afternoon'] = options.afternoon
    din['Dinner'] = options.dinner

    saved = sys.stdout
    ofile = file('DailyInTakeFile.json', 'a') # append mode

    for idx in CurDct.keys() :
        if int(idx) == options.ndays :
            print idx, options.ndays
            print "The Intake for day # %d exists" %options.ndays
            print "Are you sure you want to overwrite: Type [yes/no]"
            lett=sys.stdin.read()
            if "yes" in lett :
                CurDct[idx]['Morning'] = options.morning
                CurDct[idx]['Lunch'] = options.lunch
                CurDct[idx]['Afternoon'] = options.afternoon
                CurDct[idx]['Dinner'] = options.dinner
                ofile.close()
                sys.exit("Exiting after updating day # %d" % options.ndays)
            else :
                ofile.close()
                sys.exit("Exiting without update")

        else :
            sys.stdout = ofile
            print json.dumps(DailyInTake)
            print ","
            sys.stdout = saved
            ofile.close()

else :
    DailyInTake = dict()
    DailyInTake["%d" % options.ndays] = {}
    din = DailyInTake["%s" % options.ndays]
    din['Morning'] = options.morning
    din['Lunch'] = options.lunch
    din['Afternoon'] = options.afternoon
    din['Dinner'] = options.dinner

   #print DailyInTake

    saved = sys.stdout
    ofile = file('DailyInTakeFile.json', 'a') # append mode
    sys.stdout = ofile
    print json.dumps(DailyInTake)
    print ","
    sys.stdout = saved
    ofile.close()


from datetime import date, timedelta
from subprocess import call
call("cp DailyInTakeFile.json DailyInTakeFile.json.%s" % str(date.today()), shell=True)

此代码的输出 json 文件例如如下:

{"1": {"Lunch": "l3", "Dinner": "d3", "Afternoon": "a3", "Morning": "m3"}}
{"2": {"Lunch": "l3", "Dinner": "d3", "Afternoon": "a3", "Morning": "m3"}}

如您所见,它每次只是添加一个字典,而不是附加到创建的第一个字典。我只是想不出来了。任何帮助将不胜感激。


使用主要更改的代码进行更新


 saved = sys.stdout
    for idx in CurDct.keys() :
        if int(idx) == options.ndays :
            print idx, options.ndays
            print "The Intake for day # %d exists" %options.ndays
            print "Are you sure you want to overwrite: Type [yes/no]"
            lett=sys.stdin.read()
            if "yes" in lett :
                ofile = file('DailyInTakeFile.json', 'w') # write mode
                sys.stdout = ofile
                CurDct.update(DailyInTake)
                print json.dumps(CurDct)
                sys.stdout = saved
                ofile.close()
                sys.exit("Exiting after updating day # %d" % options.ndays)
            else :
                sys.exit("Exiting without update")

        else :
            ofile = file('DailyInTakeFile.json', 'w') # write mode
            sys.stdout = ofile
            CurDct.update(DailyInTake)
            print json.dumps(CurDct)
            sys.stdout = saved
            ofile.close()
4

2 回答 2

2

使用 JSON 序列化作为可变数据存储后端似乎是一个相当奇怪的解决方案。在不详细查看您的代码的情况下,我建议使用旨在以这种方式使用的解决方案之一。最适合这种情况的似乎是shelve模块。

于 2012-09-15T23:28:30.490 回答
2

根据代码,您每次都创建一个新字典。并且不要附加到文件中的旧文件。DailyInTake = dict()所以输出到文件,只是附加一个新的字典。

我的建议是。要将新字典索引添加到 CurDct as CurDct[index] = DailyInTake[index],然后将整个字典转储回文件。除了追加之外,您可以打开文件进行写入。

于 2012-09-15T23:34:06.377 回答