簡體   English   中英

繼續獲取AttributeError:“ list”對象沒有屬性“ split”錯誤

[英]Keep getting the AttributeError: 'list' object has no attribute 'split' 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()

追溯(最近一次通話最近):文件“ C:\\ Users \\ beaudouin11 \\ Desktop \\ Pythonprogramming \\ Fil och felhantering.py”,第18行,而在books.split(“ \\ n”)中未刪除時:AttributeError:' list'對象沒有屬性'split'

從這行開始, books = [books_title]書籍是一個清單

刪除[]以保留字符串。

我想這就是你想要的:

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,然后在每行末尾刪除“ \\ n”。

現在, books是包含書籍名稱的列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM