user2341103
user2341103

Reputation: 2433

Read a file, skip unwanted lines & add into a List

I have the following code where I scan every line and put in a list. If the line matches a string "New changes", I don't want to put in the list. Any suggestion on how to achieve this?

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

Upvotes: 1

Views: 186

Answers (5)

Benedict
Benedict

Reputation: 2821

Just to be different here is an incantation from the schools of reduce and regex:

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

Upvotes: 0

Kos
Kos

Reputation: 72221

Comprehensions can also accept a condition. Try:

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

or

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

Upvotes: 0

stranac
stranac

Reputation: 28206

List comprehensions can also do filtering:

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

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

You can filter within the list comprehension :

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

Upvotes: 3

nullptr
nullptr

Reputation: 2274

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

If anyone has a more pythonic way to do this, feel free to let me know.

Upvotes: 0

Related Questions