从列表中删除元素

时间:2016-06-06 03:29:33

标签: python json list

我无法从列表中删除元素,列表是从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')

该程序似乎运行没有错误只是它dosnt实际删除条目(通过索引)一旦我加载文件条目仍在那里

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

2 个答案:

答案 0 :(得分:0)

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

您可能要做的是从列表中删除该元素并覆盖该文件。

答案 1 :(得分:0)

您要做的是回写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')
相关问题