title: How to find and replace multiple lines in text file?
body: <p>I am running Python 2.7.</p>
  
  <p>I have three text files: <code>data.txt</code>, <code>find.txt</code>, and <code>replace.txt</code>.  Now, <code>find.txt</code> contains several lines that I want to search for in <code>data.txt</code> and replace that section with the content in <code>replace.txt</code>.  Here is a simple example:</p>
  
  <p><strong>data.txt</strong></p>
  
  <pre><code>pumpkin
  apple
  banana
  cherry
  himalaya
  skeleton
  apple
  banana
  cherry
  watermelon
  fruit
  </code></pre>
  
  <p><strong>find.txt</strong></p>
  
  <pre><code>apple
  banana
  cherry
  </code></pre>
  
  <p><strong>replace.txt</strong></p>
  
  <pre><code>1
  2
  3
  </code></pre>
  
  <p>So, in the above example, I want to search for all occurences of <code>apple</code>, <code>banana</code>, and <code>cherry</code> in the data and replace those lines with <code>1,2,3</code>.  </p>
  
  <p>I am having some trouble with the right approach to this as my <code>data.txt</code> is about 1MB so I want to be as efficient as possible.  One dumb way is to concatenate everything into one long string and use <code>replace</code>, and then output to a new text file so all the line breaks will be restored.</p>
  
  <pre><code>import re
  
  data = open("data.txt", 'r')
  find = open("find.txt", 'r')
  replace = open("replace.txt", 'r')
  
  data_str = ""
  find_str = ""
  replace_str = "" 
  
  for line in data: # concatenate it into one long string
      data_str += line
  
  for line in find: # concatenate it into one long string
      find_str += line
  
  for line in replace: 
      replace_str += line
  
  
  new_data = data_str.replace(find, replace)
  new_file = open("new_data.txt", "w")
  new_file.write(new_data)
  </code></pre>
  
  <p>But this seems so convoluted and inefficient for a large data file like mine.  Also, the <code>replace</code> function appears to be deprecated so that's not good.</p>
  
  <p>Another way is to step through the lines and keep a track of which line you found a match.</p>
  
  <p>Something like this: </p>
  
  <pre><code>location = 0
  
  LOOP1: 
  for find_line in find:
      for i, data_line in enumerate(data).startingAtLine(location):
          if find_line == data_line:
              location = i # found possibility
  
  for idx in range(NUMBER_LINES_IN_FIND):
      if find_line[idx] != data_line[idx+location]  # compare line by line
          #if the subsequent lines don't match, then go back and search again
          goto LOOP1
  </code></pre>
  
  <p>Not fully formed code, I know.  I don't even know if it's possible to search through a file from a certain line on or between certain lines but again, I'm just a bit confused in the logic of it all.  What is the best way to do this?  </p>
  
  <p>Thanks!</p>