title: How to properly replace the contents of text file
body: <p>I am trying to make an offline copy of this website: <a href="http://ieeeghn.org/wiki/index.php/History_of_Lossless_Data_Compression_Algorithms" rel="nofollow">ieeghn</a>. Part of this task is to download all css/js that being referred to using Beautiful Soup and modify any external link to this newly downloaded resource.</p>
  
  <p>At the moment I simply use string <code>replace</code> method. But I don't think this is effective, as I do this inside a loop, snippet below:</p>
  
  <pre><code>local_content = '' 
  for res in soup.findAll('link', {'rel': 'stylesheet'}):
              if not str(res['href']).startswith('data:'):
                  original_res = res['href']
                  res['href'] = some_function_to_download_css()
                  local_content = local_content.replace(original_res, res['href'])
  </code></pre>
  
  <p>I only save resource for non-embedding resource that start with <code>data:</code>. But the problem is, that <code>local_content = local_content.replace(original_res, res['href'])</code> may lead to the problem that I only able to modify one external resource into local resource. The rest still refer to online version of the resource.</p>
  
  <p>I am guessing that because local_content is a very long string (have a look at the ieeghn source), this didn't work out well.</p>
  
  <p>How do you properly replace content of a string for a given pattern?
  Or do I have to store this first to a file and modify it there?</p>
  
  <p><strong>EDITED</strong>
  I found the problem was in this line of code:</p>
  
  <pre><code> original_res = res['href']
  </code></pre>
  
  <p>BSoup will somehow sanitized the href string. In my case, <code>&amp;amp;</code> will be changed to <code>&amp;</code>.  As I am trying to replace the original <code>href</code> into a newly downloaded local file, <code>str.replace()</code> simply won't find this original value. Either I have to found a way to have original HREF or simply handle this case. Got to say, having the original HREF is the best way</p>