<blockquote class="quote light-black dark-border-color"><div class="quote light-border-color">
<div class="quote-author" style="font-weight: bold;">Francesco Pietra wrote:</div>
<div class="quote-message">
Please, how to adapt the following script (to delete blank lines) to delete
lines containing a specific word, or words?

f=open("output.pdb", "r")
for line in f:
        line=line.rstrip()
        if line:
                print line
f.close()

If python in Linux accepts lines beginning with # as comment lines, please also
a script to comment lines containing a specific word, or words, and back, to
remove #.
</div>
</div></blockquote>


<p>Well the simplest way in python using the stream for data or configuration or something IMHO would be to use a filter, list comprehension or generator expression:</p>

<pre>
# filter (puts it all in memory)
lines = filter(lambda line: not line.lstrip().startswith('#'), open("output.pdb", "r"))

# list comprehension (puts it all in memory)
lines = [line for line in open("output.pdb", "r") if not line.lstrip().startswith('#')]

# generator expression (iterable, has .next(), not kept in memory)
lines = (line for line in open("output.pdb", "r") if not line.lstrip().startswith('#'))
</pre>

<p>Check out <a href="http://rgruet.free.fr/PQR25/PQR2.5.html" target="_top" rel="nofollow"> http://rgruet.free.fr/PQR25/PQR2.5.html</a> for some quick hints.</P>
<br><hr align="left" width="300">
View this message in context: <a href="http://www.nabble.com/Delete-lines-containing-a-specific-word-tp14651102p14660373.html">Re: Delete lines containing a specific word</a><br>
Sent from the <a href="http://www.nabble.com/Python---python-list-f2962.html">Python - python-list mailing list archive</a> at Nabble.com.<br>