How to remove multiple lines from a file with python

家住魔仙堡 提交于 2021-02-17 06:39:08

问题


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

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

This works well for one line but how can I remove other (multiple) lines as well?


回答1:


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()


来源:https://stackoverflow.com/questions/63114216/how-to-remove-multiple-lines-from-a-file-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!