【发布时间】: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
【问题讨论】:
-
那是因为您正在从加载的列表中删除笑话。您永远不会真正将数据写回文件。所以文件中的数据永远不会改变。