[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Delete lines containing a specific word

Matt Nordhoff

1/6/2008 5:40:00 PM

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.)
--
1 Answer

Grant Edwards

1/6/2008 7:15:00 PM

0

On 2008-01-06, Matt Nordhoff <mnordhoff@mattnordhoff.com> wrote:

>> Please, how to adapt the following script (to delete blank lines) to delete
>> lines containing a specific word, or words?

> If you're on Linux, why not just use grep?
>
> $ grep -v theword output.pdb

And if you're on Windows, install Cygwin, and then use grep. Or
install any of about a half-dozen native Win23 implementations
of grep.

--
Grant Edwards grante Yow! I'm having a BIG BANG
at THEORY!!
visi.com