【发布时间】:2020-03-05 04:43:51
【问题描述】:
我不知道我应该怎么做才能从文件中删除这本书。
我的代码根据用户的输入来确定他们要从列表中删除哪本书。然后我打开文本文件并阅读它。
我使用.strip()进行了研究,但似乎不起作用,我不熟悉.strip()的功能
def delete_book():
book_to_delete = input('Please input the name of the book that will be removed from the library: ')
with open("listOfBook.txt", "r") as list_of_books:
books = list_of_books.readlines()
with open('listOfBook.txt', 'w') as list_of_books:
for book in books:
if book.strip('\n') != book_to_delete:
list_of_books.write(book)
print(book_to_delete, 'had been removed from the library data base')
input('Please press enter to go back to staff menu')
这是我的文本文件 (listOfBook.txt):
The Great Gatsby
To Kill a Mockingbird
Harry Potter and the Sorcerer's Stone
1984
【问题讨论】:
-
您的代码大部分是正确的只要行上没有其他空格。因此,如果您的行类似于
"The Great Gatsby \n",那么.strip"\n")会产生"The Great Gatsby ",这将不等于"The Great Gatsby"。
标签: python python-3.x file text