title: More streamline way to count lines in file (python)
body: <p>I wrote this to retrieve FASTA sequences of a list of protein accession numbers (acc_list.txt), each on a new line, and write them to a txt file (prot_list).</p>
  <pre><code>x=0
  with open(&quot;acc_list.txt&quot;,&quot;r&quot;) as input:
      number = sum(1 for items in input) ###
  with open(&quot;acc_list.txt&quot;,&quot;r&quot;) as input:
      with open (&quot;prot_list.txt&quot;,&quot;w&quot;) as output:
          for acc in input:
              handle = Entrez.efetch(db=&quot;protein&quot;,id=acc,rettype=&quot;fasta&quot;)
              x+=1
              print(&quot;Dealing with&quot;, str(acc.strip()), str(x), &quot;out of&quot;, str(number), sep=&quot; &quot;)
              output.write(handle.read())
  </code></pre>
  <p>It is a big list so the penultimate line gives me an idea of the progress.</p>
  <p>As you can see, <code>number = sum(1 for items in input)</code> gives the total number of lines, but I have to open and close the file separate, because if I put that under the latter <code>with</code> statement, i.e.</p>
  <pre><code>x=0
  with open(&quot;acc_list.txt&quot;,&quot;r&quot;) as input:
      with open (&quot;prot_list.txt&quot;,&quot;w&quot;) as output:
          for acc in input:
              number = sum(1 for items in input) ###
              handle = Entrez.efetch(db=&quot;protein&quot;,id=acc,rettype=&quot;fasta&quot;)
              x+=1
              print(&quot;Dealing with&quot;, str(acc.strip()), str(x), &quot;out of&quot;, str(number), sep=&quot; &quot;)
              output.write(handle.read())
  </code></pre>
  <p>it stops after counting items and gives no other outputs.
  I'm guessing this is because <code>number = sum(1 for items in input)</code> iterates through the file and ends the iteration too.</p>
  <p>I am curious as to whether there is a more efficient way to obtain the number of lines in a file? I can imagine that if I work with an even bigger list, there may be problems with my approach. I've seen older answers and they all involve iterating through the file first.</p>