How to remove multiple lines from a file with python

后端 未结 1 1705
忘了有多久
忘了有多久 2021-01-27 09:51

I\'m trying to remove lines from a file using this code:

with open(\'example_file\', \'r\') as file:
    file_content = fil         


        
1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-27 10:07

    You could do it using and.

    ...
    
    with open('example_file', 'w') as new_file:
        for line in file_content:
            currentLine = line.strip("\n")
            if currentLine != 'example_line_1' and currentLine != 'example_line_2':
                new_file.write(line)
    new_file.close()
    

    but that gets too big, too fast. You could also use an array with words you wish to remove from a line and then just check if the current line consists of any of those words:

    ...
    words = ["example_line_1", "example_line_2", "foobar"]
    with open('example_file', 'w') as new_file:
        for line in file_content:
            currentLine = line.strip("\n")
            if currentLine not in words:
                new_file.write(line)
    new_file.close()
    

    0 讨论(0)
提交回复
热议问题