title: Using the string .replace() function to update lines in a text file
body: <p>I'm attempting to read a text file and then if the substring doesn't match up with expected value, I want to replace that substring with a curated value. My current code is above along with a sample .txt file.</p>
  
  <pre><code>def update_atom_count(self, input_file):
      count = 0
      readFile = open(input_file, 'rt')
      writeFile = open(input_file, 'wt')
      for line in readFile:
          if line[0:6] == 'ATOM  ' or line[0:6] == 'TER   ':
              count += 1
              num = line[6:11]
              if int(num) != count:
                  writeFile.write(line.replace(num, str(count)))
      writeFile.close()
  </code></pre>
  
  <p>Sample .txt file:</p>
  
  <pre class="lang-none prettyprint-override"><code>ATOM   1850  OG1 THR A 225     -17.240  12.451  -7.500  1.00 62.47           O
  ATOM   1851  CG2 THR A 225     -16.343  13.019  -9.660  1.00 56.69           C
  ATOM   1852  N   GLN A 226     -13.575  14.217  -9.123  1.00 57.64           N
  ATOM   1853  CA  GLN A 226     -12.637  14.556 -10.203  1.00 68.89           C
  ATOM   1854  C   GLN A 226     -11.192  14.229  -9.816  1.00 55.30           C
  ATOM   1855  O   GLN A 226     -10.255  14.468 -10.580  1.00 40.73           O
  ATOM   1856  CB  GLN A 226     -12.774  16.025 -10.644  1.00 82.60           C
  ATOM   1857  CG  GLN A 226     -12.264  16.309 -12.072  1.00 72.63           C
  ATOM   1858  CD  GLN A 226     -12.294  17.790 -12.444  0.39 66.96           C
  ATOM   1859  OE1 GLN A 226     -12.864  18.615 -11.726  1.00 74.47           O
  ATOM   1860  NE2 GLN A 226     -11.673  18.130 -13.572  1.00 46.12           N
  ATOM   1861  N   ASP A 227     -11.025  13.673  -8.624  1.00 32.42           N
  ATOM   1862  CA  ASP A 227      -9.731  13.184  -8.201  1.00 38.31           C
  ATOM   1863  C   ASP A 227      -9.679  11.646  -8.233  1.00 45.89           C
  </code></pre>
  
  <p>My goal is to replace in the second "column" of the text which is <code>' 1850'</code> with <code>'    1'</code> (the extra spacing is for formatting). The output I am expecting is:</p>
  
  <pre class="lang-none prettyprint-override"><code>ATOM      1  CG2 THR A 225     -16.343  13.019  -9.660  1.00 56.69           C
  ATOM      2  N   GLN A 226     -13.575  14.217  -9.123  1.00 57.64           N
  ...
  </code></pre>