Delete lines containing a specific word

Matt Nordhoff mnordhoff at mattnordhoff.com
Sun Jan 6 12:40:00 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 #.
> 
> Thanks
> francesco pietra

If you're on Linux, why not just use grep?

$ grep -v theword output.pdb

Otherwise, just replace "if line:" with "if 'theword' not in line:".

Thanks to rstrip and print, the script changes the file's line endings
to the platform's default one. "rstrip()" also removes other types of
whitespace, like spaces and tabs.

I'm not sure how that script handles different line endings in the file.
Might want to use 'rb' instead of 'r' to open the file in binary mode on
Windows (to also help with other issues), or 'rU' or 'rbU' to use
Python's universal newline mode.)
-- 



More information about the Python-list mailing list