title: Search the word, and replace the whole line containing the word in a file in Python using fileinput
body: <p>I want to search a particular word in a text file. For each line,where the word is present, I want to completely change the line by a new text.</p>
  
  <p>I want to achieve this using <code>fileinput</code> module of python. There are two observation, I am seeing with following variations :-</p>
  
  <p><strong>Code piece 1 :-</strong></p>
  
  <pre><code>text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
  new_text = "mov9 = Alice in Wonderland"
  x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
  for line in x:
      if text in line:
          line = new_text
          print line,
  x.close()
  </code></pre>
  
  <p>The above piece of code wipes out all the content of the file, and writes the <code>new_text</code> i.e. the file content is only </p>
  
  <blockquote>
    <p>mov9 = Alice in Wonderland</p>
  </blockquote>
  
  <p><strong>Code Piece 2 :-</strong> </p>
  
  <pre><code>text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
  new_text = "mov9 = Alice in Wonderland"
  x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
  for line in x:
      if text in line:
          line = line.replace(text, new_text)
          print line,
  x.close()
  </code></pre>
  
  <p>The above piece of code, even though adds the needed line i.e. <code>new_text</code> where <code>text</code> is found, but doesn't deletes the line, but keeps the previous data also.</p>
  
  <p>That is if the line was earlier :-</p>
  
  <pre><code>mov9 = Fast &amp; Furios
  </code></pre>
  
  <p>after running the above piece of code it becomes :- </p>
  
  <pre><code>mov9 = Alice in WonderlandFast &amp; Furios
  </code></pre>
  
  <p>And other content of the files remain untouched, not deleted as in code in Code piece 1.</p>
  
  <p>But my goal is to find the word <code>mov9 =</code>, and whatever is present along with it, I want to replace the whole line as <code>mov9 = Alice in Wonderland</code>.</p>
  
  <p>How can I achieve that? Thanks in advance....</p>