Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Delete lines containing a specific word

Reply
Thread Tools

Re: Delete lines containing a specific word

 
 
Matt Nordhoff
Guest
Posts: n/a
 
      01-06-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.)
--
 
Reply With Quote
 
 
 
 
Grant Edwards
Guest
Posts: n/a
 
      01-06-2008
On 2008-01-06, Matt Nordhoff <(E-Mail Removed)> 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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Delete lines containing a specific word Francesco Pietra Python 3 01-07-2008 12:43 PM
Re: Delete lines containing a specific word Francesco Pietra Python 6 01-07-2008 03:57 AM
Fwd: Delete lines containing a specific word Francesco Pietra Python 0 01-06-2008 05:44 PM
Selecting directories containing specific fileglobs Eden Cardim Perl Misc 11 03-13-2006 04:42 PM
To delete few lines and add few lines at the end of a text file using c program Murali C++ 2 03-09-2006 04:45 PM



Advertisments