Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would stack generator expressions:</p> <pre><code>with open(filename) as f_in: lines = (line.rstrip() for line in f_in) # All lines including the blank ones lines = (line for line in lines if line) # Non-blank lines </code></pre> <p>Now, <code>lines</code> is all of the non-blank lines. This will save you from having to call strip on the line twice. If you want a list of lines, then you can just do:</p> <pre><code>with open(filename) as f_in: lines = (line.rstrip() for line in f_in) lines = list(line for line in lines if line) # Non-blank lines in a list </code></pre> <p>You can also do it in a one-liner (exluding <code>with</code> statement) but it's no more efficient and harder to read:</p> <pre><code>with open(filename) as f_in: lines = list(line for line in (l.strip() for l in f_in) if line) </code></pre> <h2>Update:</h2> <p>I agree that this is ugly because of the repetition of tokens. You could just write a generator if you prefer:</p> <pre><code>def nonblank_lines(f): for l in f: line = l.rstrip() if line: yield line </code></pre> <p>Then call it like:</p> <pre><code>with open(filename) as f_in: for line in nonblank_lines(f_in): # Stuff </code></pre> <h2>update 2:</h2> <pre><code>with open(filename) as f_in: lines = filter(None, (line.rstrip() for line in f_in)) </code></pre> <p>and on CPython (with deterministic reference counting)</p> <pre><code>lines = filter(None, (line.rstrip() for line in open(filename))) </code></pre> <p>In Python 2 use <code>itertools.ifilter</code> if you want a generator and in Python 3, just pass the whole thing to <code>list</code> if you want a list.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload