title: write a text file in Python, line by line
body: <p>I need to write a text file, line by line. This code is printing a text line by line, but only the last line is stored in the result.txt file.</p>
  
  <pre><code>import re
  import fileinput
  for line in fileinput.input("test.txt"):
      new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
      print new_str
  open('result.txt', 'w').write(new_str)
  </code></pre>