Delete lines containing a specific word

sj26 sj26 at sj26.com
Mon Jan 7 02:46:21 EST 2008



Francesco Pietra wrote:
> 
> 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 #.
> 

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:



# 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('#'))


Check out  http://rgruet.free.fr/PQR25/PQR2.5.html 
http://rgruet.free.fr/PQR25/PQR2.5.html  for some quick hints.

-- 
View this message in context: http://www.nabble.com/Delete-lines-containing-a-specific-word-tp14651102p14660373.html
Sent from the Python - python-list mailing list archive at Nabble.com.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080106/213afd4b/attachment-0001.html>


More information about the Python-list mailing list