我有一个文件,其中每一行都以数字开头。用户可以通过输入用户想要删除的行号来删除行。
我遇到的问题是设置打开它的模式。当我使用a+
时,原始内容仍然存在。但是,添加到文件末尾的是我想要保留的行。另一方面,当我使用 时w+
,整个文件都会被删除。我确信有比使用w+
模式打开它、删除所有内容、然后重新打开它并附加行更好的方法。
def DeleteToDo(self):
print "Which Item Do You Want To Delete?"
DeleteItem = raw_input(">") #select a line number to delete
print "Are You Sure You Want To Delete Number" + DeleteItem + "(y/n)"
VerifyDelete = str.lower(raw_input(">"))
if VerifyDelete == "y":
FILE = open(ToDo.filename,"a+") #open the file (tried w+ as well, entire file is deleted)
FileLines = FILE.readlines() #read and display the lines
for line in FileLines:
FILE.truncate()
if line[0:1] != DeleteItem: #if the number (first character) of the current line doesn't equal the number to be deleted, re-write that line
FILE.write(line)
else:
print "Nothing Deleted"
这是典型文件的样子
1. info here
2. more stuff here
3. even more stuff here