如何从文件中删除以特定单词开头的行 python3

How to remove lines from a file starting with a specific word python3

我正在做这个作为一项任务。所以,我需要读取一个文件并删除以特定单词开头的行。

fajl = input("File name:")
rec = input("Word:")
        
def delete_lines(fajl, rec):
    with open(fajl) as file:
        text = file.readlines()
        print(text)
        for word in text:
            words = word.split(' ')
            first_word = words[0]
            for first in word:
                if first[0] == rec:
                    text = text.pop(rec)
                    return text
                    print(text)
                return text

delete_lines(fajl, rec)

在最后一个for循环中,我完全失去了对自己所做事情的控制。首先,我不能使用 pop。因此,一旦找到该词,我就需要以某种方式删除以该词开头的行。此外,我的方法还有一个小问题,那就是 first_word 让我得到第一个词,但是 , 如果它存在的话。

文件中的示例文本(file.txt):

这是一行中的一些文字。

文字无关。

这将是一些具体的内容。

然而,事实并非如此。

这简直是胡说八道。

rec = input("Word:") --- This

输出:

文字无关。

然而,事实并非如此。

在遍历数组时不能修改它。但是你可以迭代一个副本来修改原来的

fajl = input("File name:")
rec = input("Word:")
        
def delete_lines(fajl, rec):
    with open(fajl) as file:
        text = file.readlines()
        print(text)
        # let's iterate over a copy to modify
        # the original one without restrictions 
        for word in text[:]:
            # compare with lowercase to erase This and this
            if word.lower().startswith(rec.lower()):
                # Remove the line 
                text.remove(word)
    newtext="".join(text) # join all the text
    print(newtext) # to see the results in console
    # we should now save the file to see the results there
    with open(fajl,"w") as file:
        file.write(newtext)

print(delete_lines(fajl, rec))

已使用您的示例文本进行测试。如果你想删除“这个”。 startswith 方法将类似地擦除“this”或“this”。这只会删除文本,而不会留下任何空行。如果您不想要它们,您也可以与 "\n" 进行比较并删除它们