Reputation: 636
Trying to read a txt file and filter irrelevant lines. Some lines are random strings, some being with '#' hashtag character.
base_txt = open(path, 'rU')
txt = base_txt.readlines()
txt = [x for x in base_txt if x.startswith('#')]
print txt
print len(txt)
The output is an empty list. If I print txt before the list comprehension then it prints out all the strings in the file.
Is there a syntax error I'm doing?
Upvotes: 0
Views: 78
Reputation: 1868
Your code is ok, you're just looping over the wrong variable. It should be
txt = [x for x in txt if x.startswith('#')]
instead of
txt = [x for x in base_txt if x.startswith('#')]
Upvotes: 1