Python - Counting blank lines in a text file
<p>Let's say I have a file with the following content(every even line is blank):<br></p>

<blockquote>
  <p>Line 1 <br><br> Line 2 <br><br> Line 3 <br><br> ...</p>
</blockquote>

<p>I tried to read the file in 2 ways:<br></p>

<pre><code>count = 0
for line in open("myfile.txt"):
   if line == '':                   #or if len(line) == 0
     count += 1
</code></pre>

<p>and<br></p>

<pre><code>count = 0 
file = open('myfile.txt')
lines = file.readlines()
for line in lines:
   if line == '':                   #or if len(line) == 0
     count += 1
</code></pre>

<p>But <code>count</code> always remains 0. How can I count the number of blank lines?</p>

<p>When you use <code>readlines()</code> function, it doesn't automatically remove the EOL characters for you. So you either compare against the end of line, something like:</p>

<pre><code>if line == os.linesep:
    count += 1
</code></pre>

<p>(you have to import <code>os</code> module of course), or you strip the line (as suggested by @khelwood's comment on your question) and compare against <code>''</code> as you are doing.</p>

<p>Notice that using <code>os.linesep</code> might not necessarily work as you would expect if you are running your program on a certain OS, e.g. MacOS, but the file you are checking is from a different OS, e.g. Linux, as the line ending will be different. So to check for all cases you have to do something like:</p>

<pre><code>if line == '\n' or line == '\r' or line == '\r\n':
    count += 1
</code></pre>

<p>Hope this helps.</p>

python file lines