阅读文件,跳过不需要的行&添加到列表中

时间:2013-05-02 19:40:46

标签: python

我有以下代码,我扫描每一行并放入一个列表。如果该行匹配 一个字符串“New changes”,我不想把它放在列表中。有关如何实现这一目标的任何建议吗?

with open('file.txt', 'rb') as f:
    mainlist = [line.strip() for line in f]

5 个答案:

答案 0 :(得分:3)

您可以在列表理解中进行过滤:

mainlist = [line.strip() for line in f if line.strip() !=  "New changes"]

答案 1 :(得分:2)

列表推导也可以进行过滤:

mainlist = [line.strip() for line in f if "New changes" not in line]

答案 2 :(得分:0)

with open('file.txt', 'rb') as f:
    mainlist = []
    for line in f:
        s = line.strip()
        if s != "New changes":
            mainlist.append(s)

如果有人有更多的pythonic方法,请随时告诉我。

答案 3 :(得分:0)

理解也可以接受一个条件。尝试:

mainlist = [line.strip() for line in f if line != "New changes"]

mainlist = [line.strip() for line in f if "New changes" not in line]

答案 4 :(得分:0)

这里的不同之处是来自reduce和regex学校的咒语:

import re
with open('file.txt', 'rb') as f:
  mainlist = reduce(lambda x, y: x+re.findall("^((?!.*New changes).*)\n?$", y), f.readlines(), [])