【发布时间】:2016-04-28 17:01:50
【问题描述】:
我将如何从 txt 文件中删除键和键值?例如,如果用户想从此文件中删除一个叫 Sarah 的人:
Joe,Bloggs,J.bloggs@example.com,01269 512355, 1, 0, 0, 0,
Sarah,Brown,S.brown@example.com,01866 522555, 1, 0, 0, 0,
…
目前我有以下:
L = open("players.txt","r+")
delete_name1 = raw_input ("Enter the first name of the person you wish to delete: ")
for line in L:
s = line.strip()
string = s.split(",")
if delete_name1 == string[0]:
del string[:8] # Doesn't work
print delete_name1 + " has been deleted."
L.close() # Closes the file to free us usage space.
代码被接受,但不会更改 txt 文件。我觉得我必须将更新后的信息写回 txt 文件,但我不知道该怎么做。
Please select an option: 2
Enter the first name of the person you wish to delete: Sarah
Sarah has been deleted
【问题讨论】:
-
这个问题太笼统了。提供您当前的尝试并描述您遇到的问题。
-
欢迎!请查看stackoverflow.com/help/how-to-ask。您也可以编写一个文本文件外观的示例。到目前为止你做了什么,你不明白什么?
-
将整个文件存储到某个数据结构中,从数据结构中删除Sarah的信息,然后将整个数据结构写回文件中。
-
感谢你们的快速帮助。珍惜你的时间。我会按照你们所说的,看看它是否有效。