Removing lines from a file using python
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/7081882/python-3-regular-expression-to-find-multiline-comment">Python 3 regular expression to find multiline comment</a>  </p>
</blockquote>



<p>I need some inputs on how this can be done,really appreciate your inputs,I looked at other posts but none of them matches my requirement.</p>

<p><a href="http://stackoverflow.com/questions/7276454/how-to-remove-line-from-the-file-in-python">How to remove line from the file in python</a>
http://stackoverflow.com/questions/2064184/remove-lines-from-textfile-with-python</p>

<p>I need to match a multi-line comment in a file based on a input string provided.</p>

<p>Example:-</p>

<p>Lets say if the file "test.txt" has the following comment,if inputstring="This is a test, script written" this comment needs to be deleted from the file</p>

<pre><code>import os
import sys

import re
import fnmatch

def find_and_remove(haystack, needle):
    pattern = re.compile(r'/\*.*?'+ needle + '.*?\*/', re.DOTALL)
    return re.sub(pattern, "", haystack)

for path,dirs,files in os.walk(sys.argv[1]):
    for fname in files:
        for pat in ['*.cpp','*.c','*.h','*.txt']:
            if fnmatch.fnmatch(fname,pat):
                fullname = os.path.join(path,fname)
                with open(fullname, "r") as f:
                    find_and_remove(f, r"This is a test, script written")
</code></pre>

<p>Error:-</p>

<pre><code>Traceback (most recent call last):
  File "comment.py", line 16, in &lt;module&gt;
    find_and_remove(f, r"This is a test, script written")
  File "comment.py", line 8, in find_and_remove
    return re.sub(pattern, "", haystack)
  File "/usr/lib/python2.6/re.py", line 151, in sub
    return _compile(pattern, 0).sub(repl, string, count)
TypeError: expected string or buffer
</code></pre>
