Re: Delete lines containing a specific word

Discussion in 'Python' started by Matt Nordhoff, Jan 6, 2008.

  1. 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.)
    --
     
    Matt Nordhoff, Jan 6, 2008
    #1
    1. Advertising

  2. On 2008-01-06, Matt Nordhoff <> 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
     
    Grant Edwards, Jan 6, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Murali
    Replies:
    2
    Views:
    609
    Jerry Coffin
    Mar 9, 2006
  2. Francesco Pietra

    Delete lines containing a specific word

    Francesco Pietra, Jan 6, 2008, in forum: Python
    Replies:
    3
    Views:
    807
  3. Francesco Pietra

    Fwd: Delete lines containing a specific word

    Francesco Pietra, Jan 6, 2008, in forum: Python
    Replies:
    0
    Views:
    273
    Francesco Pietra
    Jan 6, 2008
  4. Francesco Pietra

    Re: Delete lines containing a specific word

    Francesco Pietra, Jan 6, 2008, in forum: Python
    Replies:
    6
    Views:
    294
    Steven D'Aprano
    Jan 7, 2008
  5. Eden Cardim
    Replies:
    11
    Views:
    204
    Eden Cardim
    Mar 13, 2006
Loading...

Share This Page