我有一个文件,每一行都以一个数字开头。用户可以通过输入要删除的行的数字来删除该行。
我遇到的问题是设置打开模式。当我使用`a+`时,原始内容仍然存在。但是,我想保留的行被附加到文件末尾。另一方面,当我使用`w+`时,整个文件都被删除了。我确定有比使用`w+`模式打开它,删除所有内容,然后重新打开并追加行的更好方法。
这是一个典型文件的样子。
我遇到的问题是设置打开模式。当我使用`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
truncate()
的文档指出:“如果提供了可选的大小参数,则文件将被截断为该大小。大小默认为当前位置。”由于readlines()
读取文件中的所有内容,当前位置可能是文件末尾。正如我所说,您需要在删除行之前截断文件,然后写出所有行。 - millimoose