Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中从文本文件中删除特定行_Python_Python 3.x_File_Text - Fatal编程技术网

如何在python中从文本文件中删除特定行

如何在python中从文本文件中删除特定行,python,python-3.x,file,text,Python,Python 3.x,File,Text,我不知道该怎么做才能把书从档案中删除 我的代码接受用户的输入,以确定他们要从列表中删除哪本书。然后我打开文本文件并读取它 我使用.strip()进行了研究,但它似乎不起作用,而且我不熟悉.strip() 这是我的文本文件(listOfBook.txt): 伟大的盖茨比 杀死一只知更鸟 哈利·波特与魔法石 1984 我对代码做了细微的更改,希望能够解释您遇到的一些问题(有些可能只是问题的格式) def delete_book(): book_to_delete=input('请输入将从库中删除的

我不知道该怎么做才能把书从档案中删除

我的代码接受用户的输入,以确定他们要从列表中删除哪本书。然后我打开文本文件并读取它

我使用
.strip()
进行了研究,但它似乎不起作用,而且我不熟悉
.strip()

这是我的文本文件(
listOfBook.txt
):

伟大的盖茨比 杀死一只知更鸟 哈利·波特与魔法石 1984
我对代码做了细微的更改,希望能够解释您遇到的一些问题(有些可能只是问题的格式)


def delete_book():
book_to_delete=input('请输入将从库中删除的图书的名称:')
打开(“listOfBook.txt”、“r”)作为书籍列表:
books=图书列表。readlines()
打开('listOfBook.txt','w')作为书籍列表:
对于书本中的书本:
如果book.strip('\n').strip()!=书籍_至_删除:#代码更改
列出所有的书。写(书)
其他:#代码更改
打印(从“已从图书馆数据库中删除”一书)
输入('请按enter键返回员工菜单')
首先,我在第7行的支票中添加了第二个
.strip()
。这将删除任何前导或尾随空格(这将导致不匹配)

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


希望这能如您所愿。

您的代码基本上是正确的,可以正确地从行中删除
\n
字符

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

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

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

    尝试使用或打印该行,这将使它们看起来像Python字符串文字。如果您只使用英文文本,那么
    ascii
    repr()
    之间的差异其实并不重要;重要的是,您可以通过某种方式查看字符串值,从而更容易发现诸如空格之类的内容

    只需将
    print(“book的值是:”,ascii(book))
    print(“book\u to\u delete的值是:”,ascii(book\u to\u 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()
    删除了这些额外的空格

    另外,请注意,用户也可能会添加额外的空格,请务必删除这些空格

  • 用户可以使用不同的大小写混合字符。您可以在两个值上使用`来确保忽略大小写中的差异:

    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():
,因此仍然是函数的一部分,而不是任何其他块的一部分:

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\u to\u delete
不匹配的行写入文件并且文件已关闭后,才会执行该操作。请注意,在上面的示例中,我还将
.strip(“\n”)
更改为
.strip()
,并向用户输入添加了一个额外的
strip()
调用。

只要行上没有其他空格,您的代码基本上是正确的。因此,如果你的台词像《了不起的盖茨比》,那么
.strip“\n”)
就产生了《了不起的盖茨比》,它不等于《了不起的盖茨比》。我希望它有意义,请澄清一下
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)
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)