英文:
How to update .txt file list after deleting an item in list box
问题
我是Python和TKinter的新手。
我无法弄清楚如何编写这个代码。
假设我的.txt文件包含3个名称:
["Bob", "Mark", "John"]
在从显示在列表框中的列表中删除"Mark"之后(通过.curselection()
和listbox.delete(selected_name)
),我希望.txt文件中的列表更新为:
["Bob", "John"]
我该如何编写代码?
这是我的尝试:
selected_name = name_list.curselection()
name_list.delete(selected_name)
with open("name_list.txt", 'w') as f:
f.close()
f.write(name_list.get())
它返回一个列表框索引错误,因为我不知道如何获取列表框项目。
如果我的解释有点混乱,我道歉。
英文:
I'm new to Python and TKinter.
I can't figure out how to code this one.
Let's say my .txt file consists of 3 names:
["Bob", "Mark", "John"]
After deleting "Mark"
from the list that is displayed in a list box (via .curselection()
and listbox.delete(selected_name)
). I want the list from the .txt file to update as:
["Bob", "John"]
How do I code this?
This was my attempt:
selected_name = name_list.curselection()
name_list.delete(selected_name)
with open("name_list.txt", 'w') as f:
f.close()
f.write(name_list.get())
It returns a list box index error since I don't know how to get list box items.
Apologies if my explanation is all around the place.
答案1
得分: 1
以下是翻译好的代码部分:
文件内容表示有效的 JSON。
您需要打开文件以进行读写操作。将文件内容加载,以便将其作为 Python 列表访问。从列表中删除名称。重新写入文件。
import json
import os
def remove_name(filename, name):
with open(filename, 'r+') as data:
try:
lst = json.load(data)
lst.remove(name)
data.seek(0, os.SEEK_SET)
json.dump(lst, data)
data.truncate()
except ValueError:
pass
remove_name('name_list.txt', 'Mark')
编辑:
原始问题在文件中存储名称的方式方面存在误导。实际上,它们是逐行存储的。因此:
import os
def remove_name(filename, name):
with open(filename, 'r+') as data:
names = data.readlines()
data.seek(0, os.SEEK_SET)
for _name in names:
if _name.rstrip() != name:
data.write(_name)
data.truncate()
希望这对您有所帮助。
英文:
The file contents represent valid JSON.
You will need to open the file for reading and writing. Load the file contents so they're accessible as a Python list. Remove the name from the list. Rewrite the file.
import json
import os
def remove_name(filename, name):
with open(filename, 'r+') as data:
try:
lst = json.load(data)
lst.remove(name)
data.seek(0, os.SEEK_SET)
json.dump(lst, data)
data.truncate()
except ValueError:
pass
remove_name('name_list.txt', 'Mark')
EDIT:
It seems that the original question is misleading in terms of the way the names are stored in the file. They are, in fact, stored line by line. Therefore:
import os
def remove_name(filename, name):
with open(filename, 'r+') as data:
names = data.readlines()
data.seek(0, os.SEEK_SET)
for _name in names:
if _name.rstrip() != name:
data.write(_name)
data.truncate()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论