关于python:继续获取AttributeError:’list’对象没有属性’split’错误

Keep getting the AttributeError: 'list' object has no attribute 'split' error

我在管理我的代码时遇到了一个问题,我想知道为什么会出现这个错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
books_title = open("books.txt","a")
books = [books_title]
books_title.write("Narnia"+"
"
)
books_title.write("Sagan om ringen"+"
"
)
books_title.write("Snabba Cash"+"
"
)
books_title.write("Star Wars"+"
"
)
books_title.write("Harry Potter"+"
"
)
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("
"
):
 print("Boken du f?rs?ker ta bort finns inte")
 remove = input("Vilken bok vill du ta bort?")
for line in books.split("
"
):
 if line != remove:
    books_title.write(line +"
"
)
print("Tar bort boken {}".format(remove))
print("-"*40)
txt_file.close()

回溯(最近一次呼叫的最后一次):文件"c:userseaudouin11desktoppython programmingfil och felhanning.py",第18行,in当移除不在books.split("")中时:attributeError:"list"对象没有"split"属性


我想这就是你想要的:

1
2
3
4
5
6
with open("books.txt","r") as f:
    books = f.readlines()
    books = [book.strip() for book in books]

while remove not in books:
    print("Boken du f?rs?ker ta bort finns inte")

它一行一行地读取books.txt,然后在每行末尾去掉''。

现在,books是一个包含你的书的名字的列表。


以及这一行,books = [books_title]书是一个列表。

删除[]以保留字符串。