1

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'

Swartan
  • 13
  • 2
  • 1
    Well, like the error says, `books` is a list. Why are you trying to split it? Why do you have that variable at all? Did you mean `books_title`? – Daniel Roseman Jan 12 '19 at 12:58
  • 2
    Possible duplicate of [How to split one list in a list of x list with python?](https://stackoverflow.com/questions/25412151/how-to-split-one-list-in-a-list-of-x-list-with-python) which, itself has _two duplicates_ – chb Jan 12 '19 at 13:02

2 Answers2

0

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

Remove the [] to keep a string.

  • I get this error code instead when I remove the [] . while remove not in books.split("\n"): AttributeError: '_io.TextIOWrapper' object has no attribute 'split'. I'm really confused right now – Swartan Jan 12 '19 at 14:07
0

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.

keineahnung2345
  • 2,635
  • 4
  • 13
  • 28
  • I solved the error by just changing books = books_title.read() then: for lines in books.split("\n"): if lines != remove: print(lines) books_title.close() – Swartan Jan 13 '19 at 19:49