title: python looping through input file
body: <p>My question is related to file-input in Python, using <code>open()</code>. I have a text file <code>mytext.txt</code> with 3 lines.
  I am trying to do two things with this file: print the lines, and print the number of lines.</p>
  
  <p>I tried the following code:</p>
  
  <pre><code>input_file = open('mytext.txt', 'r')
  count_lines = 0
  for line in input_file:
      print line
  for line in input_file:
      count_lines += 1
  print 'number of lines:', count_lines
  </code></pre>
  
  <p>Result: it prints the 3 lines correctly, but prints "number of lines: 0" (instead of 3)</p>
  
  <hr>
  
  <p>I found two ways to solve it, and get it to print <code>3</code>: </p>
  
  <p>1) I use one loop instead of two</p>
  
  <pre><code>input_file = open('mytext.txt', 'r')
  count_lines = 0
  for line in input_file:
      print line
      count_lines += 1
  print 'number of lines:', count_lines
  </code></pre>
  
  <p>2) after the first loop, I define input_file again</p>
  
  <pre><code>input_file = open('mytext.txt', 'r')
  count_lines = 0
  for line in input_file:
      print line
  input_file = open('mytext.txt', 'r')
  for line in input_file:
      count_lines += 1
  print 'number of lines:', count_lines
  </code></pre>
  
  <hr>
  
  <p>To me, it seems like the definition <code>input_file = ...</code> is valid for only one looping, as if it was deleted after I use it for a loop. But I don't understand why, probably it is not 100% clear to me yet, how <code>variable = open(filename)</code> treated in Python.</p>
  
  <p>By the way, I see that in this case it is better to use only one loop. However, I feel I have to get this question clear, since there might be cases when I can/must make use of it.</p>