【问题标题】:How do I remove a specific line from a text file in python如何从python中的文本文件中删除特定行
【发布时间】: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


【解决方案1】:

您的代码大部分是正确的,它可以正确地从您的行中删除 \n 字符。

您在告诉用户该书已被删除时也存在缩进问题,但这可能是您如何在此处发布问题中的代码的问题。它不会影响您的代码如何测试每一行。

但是,从每个 book 值中删除 \n 字符并不意味着从文件中读取的字符串将与用户键入的字符串匹配:

  • 您的行可能有额外的空格。当您在文本编辑器中打开书籍文件时,这更难看到,但您可以使用更多 Python 代码来测试它。

    尝试使用repr() function 或ascii() function 打印该行,这将使它们看起来像是Python 字符串文字。如果您只使用英文文本,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 交互式会话中使用该函数:

    >>> 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"))) 通过'...' 引用的位置显示字符串更长。最后,使用不带参数的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 值并发现它是另一本书时都会执行它们。

您想要删除足够的缩进,以便仅缩进一次超过def delete_book(): 的级别,因此仍然是函数的一部分,但不是任何其他块的一部分:

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() 调用......

【讨论】:

    【解决方案2】:

    我已经稍微更改了代码,希望能够解释您遇到的一些问题(有些可能只是问题的格式)

    
    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()。这将删除任何前导或尾随空格(这将导致不匹配)

    此外,我还通过“当一本书被删除时”的报告重组了一些逻辑

    希望这能如你所愿。

    【讨论】:

      【解决方案3】:
      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)
      

      【讨论】:

      • 我希望它是有道理的,请要求澄清
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      相关资源
      最近更新 更多