[英]How do I remove a specific line from a text file in python
我不知道我應該怎么做才能從文件中刪除這本書。
我的代碼從用戶那里獲取輸入,以確定他們要從列表中刪除哪本書。 然后我打開文本文件並閱讀它。
我使用.strip()
進行了研究,但似乎它不起作用,而且我不熟悉.strip()
的 function
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
您的代碼大部分是正確的,它會正確地從您的行中刪除\n
字符。
您在告訴用戶該書已被刪除時也有縮進問題,但這可能是您如何在此處發布問題中的代碼的問題。 它不會影響您的代碼如何測試每一行。
但是,從每個book
值中刪除\n
字符並不意味着從文件中讀取的字符串將與用戶鍵入的字符串匹配:
您的行可能有額外的空格。 當您在文本編輯器中打開圖書文件時,這很難看到,但您可以使用更多的 Python 代碼來測試它。
嘗試使用repr()
function或ascii()
function來打印該行,這將使它們看起來好像是 ZA7F5F35426B927411FC9231B56382173 字符串。 如果您只使用英文文本,那么ascii
和repr()
之間的區別並不重要; 重要的是您可以以一種更容易發現諸如空格之類的東西的方式查看字符串值。
只需在循環中添加一個print("The value of book is:", ascii(book))
和print("The value of book_to_delete is:", ascii(book_to_delete))
:
with open('listOfBook.txt', 'w') as list_of_books: for book in books: print("The value of book is:", ascii(book)) print("The value of book_to_delete is:", ascii(book_to_delete)) if book.strip('\n'):= book_to_delete:
您可以從str.strip()
中刪除"\n"
參數並從開頭和結尾刪除所有空白字符以解決此問題:
if book.strip().= book_to_delete:strip():
您可以在 Python 交互式 session 中使用 function:
>>> book = "The Great Gatsby \n" >>> book 'The Great Gatsby \n' >>> print(book.strip("\n")) The Great Gatsby >>> print(ascii(book.strip("\n"))) 'The Great Gatsby ' >>> print(ascii(book.strip())) 'The Great Gatsby'
請注意print(book.strip("\n"))
並沒有真正向您顯示那里有額外的空格,但是print(ascii(book.strip("\n")))
通過'...'
引用,表示字符串更長。 最后,使用沒有 arguments 的str.strip()
刪除了那些額外的空格。
另外,請注意,用戶還可以添加額外的空格,也請刪除這些空格。
用戶可能使用不同的大寫和小寫字符組合。 您可以在兩個值上使用str.casefold()
function ` 以確保忽略大小寫的差異:
if book.strip().casefold().= book_to_delete:casefold():
您發布的代碼存在縮進問題。 線條
print(book_to_delete, 'had been removed from the library data base')
input('Please press enter to go back to staff menu')
當前縮進到if book.strip('\n'):= book_to_delete:
測試塊下,因此每次測試文件中的book
值並發現它是不同的 book 時都會執行它們。
您想刪除足夠的縮進,以便僅在超過def delete_book():
級別后縮進,因此仍然是 function 的一部分,但不是任何其他塊的一部分:
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() != book_to_delete.strip():
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')
這樣,只有在您將所有與book_to_delete
不匹配的行寫入文件並且文件已關閉后,它才會執行。 請注意,在上面的示例中,我還將.strip("\n")
更改為.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').strip() != book_to_delete: # Code Changes
list_of_books.write(book)
else: # Code Changes
print(book_to_delete, 'had been removed from the library data base')
input('Please press enter to go back to staff menu')
首先,我在第 7 行的檢查中添加了第二個.strip()
。這將刪除任何前導或尾隨空格(這將導致不匹配)
此外,我通過“當一本書被刪除”的報告重組了一些邏輯
希望這如你所願。
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 = [line.strip() for line in list_of_books]
found_book = False
for i in range(len(books)):
if books[i] == book_to_delete:
found_book = True
break
if found_book == False:
print("Book not found in the list")
else:
books.remove(book_to_delete)
open('listOfBook.txt', 'w').close()
with open('listOfBook.txt', 'w') as list_of_books:
for bookTitle in books:
list_of_books.write('%s\n' % bookTitle)
像這樣更改您的代碼
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')
此解決方案以 r/w 模式(“r+”)打開文件,並利用 seek 重置 f 指針,然后在最后一次寫入后截斷以刪除所有內容。
book_to_delete = input('Please input the name of the book that will be removed from the library: ')
with open("listOfBook.txt", "r+") as f:
d = f.readlines()
f.seek(0)
for i in d:
if i != book_to_delete:
f.write(i)
f.truncate()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.