Reputation: 2433
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
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
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
Reputation: 28206
List comprehensions can also do filtering:
mainlist = [line.strip() for line in f if "New changes" not in line]
Upvotes: 2
Reputation: 250871
You can filter within the list comprehension :
mainlist = [line.strip() for line in f if line.strip() != "New changes"]
Upvotes: 3
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