尝试执行联系人列表属性错误:'list'对象没有属性'write'



试图创建一个联系人列表,在那里你可以从.txt中添加和删除人员,我可以添加人员,但当我试图写出txt中除了我想删除的行之外的所有行时,我会遇到这行错误。我看到了其他线索,但不明白我应该改变什么。

错误:AttributeError:"list"对象没有属性"write">

from model_contact import Contact
toDo = input("Add or remove contact: ")
if toDo == "add":
name = input("Name: ")
contactlist = open("contactlist.txt", "a")
contactlist.write("n" + name)
contactlist.close()
print(name + " is now added to the contactlist!")
elif toDo == "remove":
name = input("Name of removal: ")
contactlist = open("contactlist.txt", "r")
lines = contactlist.readlines()
contactlist.close()
open("contactlist.txt", "w")
for line in lines:
if line.strip("n") != name:
lines.write(line)

只是在一个代码片段中总结上面的所有注释:

from model_contact import Contact
toDo = input("Add or remove contact: ")
name = input("Name: ") 
if toDo == "add":
with open("contactlist.txt", "a") as contactlist:
contactlist.write("n" + name)
print(name + " is now added to the contactlist!")
elif toDo == "remove":
with open("contactlist.txt", "r") as contactlist:
lines = contactlist.readlines()

with open("contactlist.txt", "w") as ncl: #cnl == new contact list 
for line in lines: # lines here are the read lines from above
if line.strip("n") != name:
ncl.write(line)

这段代码非常直接,有一个严重的缺陷,那就是第二次打开文件,如果文件很大,可能会有问题。

如果文件很大,为了减少影响,我会尝试这样做:


with open("contactlist.txt", "r+") as contactlist:
lines = contactlist.readlines()
tmp = []

for num, line in enumerate(lines):
if line.strip("n") == name:
tmp.append(num)
for num in tmp:
lines.pop(num)
contactlist.writelines(lines)

最新更新