title: Replacing a line in file moves another line to a superior one
body: <p>I have a py file like the following one:</p>
  
  <pre><code>final_data = ','.join(ordered_data.iloc[0].astype(str).values.tolist())
  runtime = boto3.client('runtime.sagemaker')
  response = runtime.invoke_endpoint(EndpointName='xgboost-whatever', #Endpoint mark                                           
                                         ContentType='text/csv',
                                         Body=final_data)
  </code></pre>
  
  <p>What I want is to replace the line with the EndpointName for another line. Taking in account the SO question <a href="https://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python">Search and replace a line in a file in Python</a> I have coded this:</p>
  
  <pre><code>def replace(file_path, subst):
      #Create temp file
      fh, abs_path = mkstemp()
      with fdopen(fh,'w') as new_file:
          with open(file_path) as old_file:
              for line in old_file:
                  if re.search('response = runtime.invoke_endpoint(.*?)#Endpoint mark',line):
                      new_file.write(line.replace(line, subst))
                  else:
                      new_file.write(line)
      #Remove original file
      remove(file_path)
      #Move new file
      move(abs_path, file_path)
  
  
  file_path = '/home/whatever'
  subst = "        response = runtime.invoke_endpoint(EndpointName='xgboost-otro', #Endpoint mark "
  
  replace(file_path, subst)
  </code></pre>
  
  <p>However, running the previous code gets me something different that what I was looking for:</p>
  
  <pre><code>final_data = ','.join(ordered_data.iloc[0].astype(str).values.tolist())
  runtime = boto3.client('runtime.sagemaker')
  response = runtime.invoke_endpoint(EndpointName='xgboost-otro', #Endpoint mark                                                                              ContentType='text/csv',
                                         Body=final_data)
  </code></pre>
  
  <p>So I lose the ContentType line, which is converted to a comment. 
  If I introduce an <code>\n</code> character at the end of <code>subst</code> it deletes the ContentType line. How could I solve it?</p>