title: file.write() the length of file without knowing the length of file beforehand - python
body: <p>I have a header line that needs to be printed at the start of the textfile, and then the next line should contain the information about how many lines of data there are.</p>
  
  <p>The final output file should contain the follow content:</p>
  
  <ol>
  <li>the header line before the first <code>\n</code></li>
  <li>the length of file (i.e. # of lines in the before the 2nd <code>\n</code></li>
  <li>the unknown lines of string </li>
  </ol>
  
  <p>The question is <strong>how can (2) content be satisfied without first knowing how many lines of strings there are?</strong></p>
  
  <p>I have been doing it as such:</p>
  
  <ol>
  <li>write the header line</li>
  <li>write a fake line of 50 <code>" "</code> characters</li>
  <li>write unknown lines of string while keeping a counter of #lines </li>
  <li>seek to the end of the header line</li>
  <li>write the #line lines in the 2nd line, leave the rest of the <code>" "</code> untouch</li>
  <li>close the file (imagine it goes up to 19GB worth of strings)</li>
  </ol>
  
  <p>For the sake of example, i use <code>random.random()</code> to generate the number of lines, and i have been doing it this way:</p>
  
  <pre><code>import random
  fout = open('testoverwrite','w')
  
  header = "%% this is a header line"
  
  print&gt;&gt;fout, header
  print&gt;&gt;fout, "".join((" ")*50)
  
  total = 0
  numrows = int(100*random.random())
  for i in range(numrows):
      j = int(100*random.random())
      total+=j
      print&gt;&gt;fout, j
  
  fout.seek(len("%% this is a header line\n"))
  #print len(str(numrows)+" "+str(total))
  if len(str(numrows)+" "+str(total)) &lt; 50:
      fout.write(str(numrows)+" "+str(total))
  
  fout.close()
  </code></pre>
  
  <p><strong>is there are better way to do this?</strong></p>