Python:从JSON模块文件中删除数据

时间:2015-10-05 19:55:17

标签: python

我目前有这个代码工作正常,但我需要能够从数据文件中删除命令数据。

这就是文件内部的样子: [[15," TomBy012"],[10," Badrob135"]]

这就是我的代码:

import json

def load_scores():
    with open("scores.json") as infile:
        return json.load(infile)

def save_scores(scores):
    with open("scores.json", "w") as outfile:
        json.dump(scores, outfile)
        print("Scores Saved")

def scoresMenu():
    print ("""Please pick a valid option from the list below

 1 » Load existing scores from the database
 2 » Save the scores from this session
 3 » Create a new score for the database
 4 » Delete specific scores from the database
""")

    menuInput = input(" Option »  ")

    if menuInput == "3":
        global scores
        name = input(" Input Your Username »  ")
        score = int(input("Input Your Score »  "))
        entry = [score, name]
        scores.append(entry)
        scores.sort(reverse=True)
        scores = scores[:10]

    elif menuInput == "1":
        print(scores)

    elif menuInput == "2":
        save_scores(scores)

    elif menuInput == "4":
        print("Work In Progress!")

    else:
        print("GoodBye! Thanks for trying our program.")
        exit

scores = load_scores()



while True:
    print(" ")
    scoresMenu()

总而言之,我想要实现的是用户输入的内容,例如,“Tomby'它会从文件中删除得分的分数和名称,因此[15," TomBy"]将被删除。我该如何实现呢?

1 个答案:

答案 0 :(得分:0)

  1. 询问用户要删除的名称
  2. 迭代列表
  3. 删除与名称匹配的项目
  4. 可能看起来像这样:

    #UNTESTED
    name = input(" Input Your Username »  ")
    for index, item in enumerate(scores):
        if item[1] == name:
            del scores[index]
            break