首页 > 解决方案 > 不断收到 AttributeError: 'list' object has no attribute 'split' 错误

问题描述

我在管理代码时遇到问题,并试图弄清楚为什么会出现此错误

books_title = open("books.txt", "a")
books = [books_title]
books_title.write("Narnia"+"\n")
books_title.write("Sagan om ringen"+"\n")
books_title.write("Snabba Cash"+"\n")
books_title.write("Star Wars"+"\n")
books_title.write("Harry Potter"+"\n")
books_title.close()

print("Böcker")
print("-"*5) 
books_title = open("books.txt", "r")
print(books_title.read())
books_title.close()

books_title = open("books.txt", "w")
remove = input("Vilken bok vill du ta bort? ")
while remove not in books.split("\n"):
 print("Boken du försöker ta bort finns inte")
 remove = input("Vilken bok vill du ta bort? ")
for line in books.split("\n"):
 if line != remove:
    books_title.write(line + "\n")
print("Tar bort boken {}".format(remove))
print("-"*40)
txt_file.close()

回溯(最近一次调用最后):文件“C:\Users\beaudouin11\Desktop\Pythonprograming\Fil och felhantering.py”,第 18 行,在而删除不在 books.split("\n"): AttributeError: ' list' 对象没有属性 'split'

标签: pythonpython-3.x

解决方案


好吧,这books = [books_title]本书是一个列表

删除 [] 以保留字符串。


推荐阅读