我在python程序上需要一些帮助。我是python的新手,现在正在学习python文件处理。如何从python中的文本文件中删除特定行?下面是我的源代码。首先,我将从用户那里得到用户输入,以确定他要从列表中删除哪本书。然后,我打开文本文件并阅读,从这一步开始,我不知道该怎么做才能从文件中删除该书。我使用.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
我在python程序上需要一些帮助。我是python的新手,现在正在学习python文件处理。如何从python中的文本文件中删除特定行?下面是我的源代码。首先,我...
像这样更改代码