如何使用python从文件中删除多行 [英] How to remove multiple lines from a file with python

查看:133
本文介绍了如何使用python从文件中删除多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码从文件中删除行:

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?

推荐答案

您可以使用 来完成.

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

这篇关于如何使用python从文件中删除多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆