简体   繁体   English

删除外部文本文件中的某些行

[英]Remove certain lines in an external textfile

I'm working on a program which should be able to handle basic library tasks. 我正在开发一个应该能够处理基本库任务的程序。 I've a problem with a class method which is suppose to offer the user the possibility to remove a certain book from the library. 我在使用类方法时遇到了问题,该方法是为用户提供从图书馆中删除某本书的可能性。 The list of books is contained on an external textfile with the following format (author, title): 书籍清单包含在外部文字档案中,格式如下(作者,书名):

  Vibeke Olsson, Molnfri bombnatt 
  Axel Munthe, Boken om San Michele

The metod I'm using is shown below: 我正在使用的方法如下所示:


def removeBook(self):
    removal_of_book = input("What's the book's titel, author you'd like to remove?: ")
    with open("books1.txt" , "r+") as li:
        new_li = li.readlines()
        li.seek(0)
        for line in new_li:
            if removal_of_book not in line:
                li.write(line)
        li.truncate()
    print(removal_of_book + " is removed from the system!")

The problem with this method is it that every row containing removal_of_book gets removed (or not rewritten on the file). 这种方法的问题在于,包含remove_of_book的每一行都被删除(或未在文件上重写)。 I know that the method is far from optimal and probably should be scratched but I'm completely lost in finding an alternative. 我知道该方法远非最佳方法,应该刮掉它,但是我完全找不到寻找替代方法。

Does anyone have a better solution to this problem? 有谁对这个问题有更好的解决方案?

You can create your lines to write into the new file on the fly using a list comprehension and then write them to the new file afterwards (using the same file name to overwrite the original file): 您可以创建行以使用列表推导功能将其实时写入新文件,然后再将其写入新文件(使用相同的文件名覆盖原始文件):

def removeBook(self):

    to_remove = input("What's the book's title, author you'd like to remove?: ")

    with open("books1.txt" , "r+") as li:

        new_li = [line for line in li.readlines() if to_remove not in line]

    new_file = open('books1.txt', 'w'); new_file.write(new_li); new_file.close()

    print(to_remove + " is removed from the system!")

Note that string membership checking is case sensitive, so you are expecting your user to match your case in the original file exactly . 请注意,字符串成员资格检查区分大小写,因此您希望用户与原始文件中的大小写完全匹配。 You might think about converting the strings to lower-case prior to performing your check using lower() . 您可能会考虑在使用lower()执行检查之前将字符串转换为小写形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM