首页 > 解决方案 > 如何从以特定单词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 循环中,我完全失去了对我正在做的事情的控制。首先,我不能使用流行音乐。所以,一旦我找到这个词,我需要以某种方式删除以那个词开头的行。此外,我的方法还有一个小问题,那就是 first_word 让我得到第一个单词,但 , 如果它存在的话。

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

这是一行中的一些文本。

文字无关紧要。

这将是一些具体的东西。

然而,事实并非如此。

这只是胡说八道。

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

输出:

文字无关紧要。

然而,事实并非如此。

标签: python-3.xfilefor-loopiowith-statement

解决方案


迭代数组时不能修改数组。但是您可以遍历副本以修改原始副本

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" 进行比较并删除它们


推荐阅读