【问题标题】:delete element from list从列表中删除元素
【发布时间】:2026-01-09 18:30:01
【问题描述】:

我无法从列表中删除元素,该列表是从 json 文件加载的。

elif choice == 'd':
    # Delete a joke.
    # See Point 7 of the "Requirements of admin.py" section of the assignment brief.
    jokeIndex = input('Joke number to delete: ')
    index = int(jokeIndex)
    file = open('data.txt', 'r')
    data = json.load(file)
    data.pop(index)
    file.close()
    print ('Joke deleted')

程序似乎运行没有错误,只是一旦我加载文件,它实际上并没有删除条目(按索引),条目仍然在那里

elif choice == 'l':
    # List the current jokes.
    # See Point 4 of the "Requirements of admin.py" section of the assignment brief.
    file = open('data.txt', 'r')
    data = json.load(file)
    file.close()
    for (index, entry) in enumerate(data):
        print (index, ')', entry['setup'])
    pass

【问题讨论】:

  • 那是因为您正在从加载的列表中删除笑话。您永远不会真正将数据写回文件。所以文件中的数据永远不会改变。

标签: python json list


【解决方案1】:

您只是删除列表元素,而不是从文件中删除元素/行。

你可以做的是从列表中删除元素并覆盖文件。

【讨论】:

    【解决方案2】:

    您要做的是写回 json 文件。我会使用json.dump(data, file, indent=4)。见下文。

    # Delete a joke.
    # See Point 7 of the "Requirements of admin.py" section of the assignment brief.
    jokeIndex = input('Joke number to delete: ')
    index = int(jokeIndex)
    file = open('jokes.txt', 'r+')
    data = json.load(file)
    data.pop(index)
    file.truncate(0)
    json.dump(data, file, indent=4)
    file.close()
    print ('Joke deleted')
    

    【讨论】:

    • raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 1 column 260 (char 259) 这是我得到的错误。我已经尝试过与您给我的解决方案类似的解决方案,一旦我尝试查看 json 文件中的内容,我就会收到该错误
    • 我不确定那个错误。我想这可能取决于您的.txt 文件的格式。我假设类似[ "one", "two", "three"]
    • entry = {'setup': jokeSetup , 'punchline': jackPunchLine} 这是加载到txt文件中的字典,格式为json