简体   繁体   中英

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

I'm having a problem managing my code and trying to figure out why I'm getting this error

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()

Traceback (most recent call last): File "C:\\Users\\beaudouin11\\Desktop\\Python programmering\\Fil och felhantering.py", line 18, in while remove not in books.split("\\n"): AttributeError: 'list' object has no attribute 'split'

Well as of this line books = [books_title] books is a list

Remove the [] to keep a string.

I guess this is what you want:

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")

It reads in books.txt line by line, and then strip the '\\n' at the end of each line.

Now books is a list containing your books' names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM