Results 1 to 8 of 8

Thread: [SOLVED] [Python] Print matching lines in a file

  1. #1
    Join Date
    Nov 2005
    Location
    Leeds, UK
    Beans
    1,634
    Distro
    Ubuntu Development Release

    [SOLVED] [Python] Print matching lines in a file

    Hi,
    This should be a pretty simple question but I can't seem to find an answer on the web. How would you do the equivalent of:

    Code:
    grep file "string"
    with python. I've found one method so far using re.

    Here it is:

    PHP Code:
        pattern re.compileVariable1 )
        
        for 
    line in data:
            
    a_match pattern.searchline )
            if ( 
    a_match ):
                print 
    line 
    The problem is that "string", or Variable1 in the code, should not be parsed for regex.

    Thanks in advance

  2. #2
    Join Date
    Aug 2007
    Location
    127.0.0.1
    Beans
    1,800
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: [Python] Print matching lines in a file

    You don't want to parse it as a regexp, then why are you using regexps in the first place?

    Matching exactly the line (w/o regexp):
    PHP Code:
    search_str "hello"
    search_file open("myfile""r")

    for 
    line in search_file:
        if 
    line.strip() == search_str:
            print 
    line

    search_file
    .close() 
    Matching a substring
    PHP Code:
    search_str "hello"
    search_file open("myfile""r")

    for 
    line in search_file:
        if 
    line.strip().find(search_str) != -1:
            print 
    line

    search_file
    .close() 
    Check string methods:
    http://docs.python.org/lib/string-methods.html

    (Extra: Add try/except IOError/finally when managing files).
    Last edited by Can+~; June 30th, 2008 at 10:05 PM.
    "Just in terms of allocation of time resources, religion is not very efficient. There's a lot more I could be doing on a Sunday morning."
    -Bill Gates

  3. #3
    Join Date
    Apr 2007
    Beans
    14,781

    Re: [Python] Print matching lines in a file

    Code:
    for line in open("unix.text"):
        if "Gurus" in line:
            print line
    Code:
    ~$cat unix.text
    Get GUMMed
    ----------
     
    The Gurus of Unix Meeting of Minds (GUMM) takes place Wednesday, April 1, 2076
    (check THAT in your perpetual calendar program), 14 feet above the ground
    directly in front of the Milpitas Gumps.  Members will grep each other by the
    hand (after intro), yacc a lot, smoke filtered chroots in pipes, chown with
    forks, use the wc (unless uuclean), fseek nice zombie processes, strip, and
    sleep, but not, we hope, od.  Three days will be devoted to discussion of the
    ramifications of whodo.  Two seconds have been allotted for a complete rundown
    of all the user-friendly features of Unix.  Seminars include "Everything You
    Know is Wrong", led by Tom Kempson, "Batman or Cat:man?" led by Richie Dennis
    "cc C?  Si!  Si!" led by Kerwin Bernighan, and "Document Unix, Are You
    Kidding?" led by Jan Yeats.  No Reader Service No. is necessary because all
    GUGUs (Gurus of Unix Group of Users) already know everything we could tell
    them.
    		-- Dr. Dobb's Journal, June 1984

  4. #4
    Join Date
    Aug 2007
    Location
    127.0.0.1
    Beans
    1,800
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: [Python] Print matching lines in a file

    Quote Originally Posted by LaRoza View Post
    Code:
    for line in open("unix.text"):
        if "Gurus" in line:
            print line
    Right, I always forget the in operator.
    "Just in terms of allocation of time resources, religion is not very efficient. There's a lot more I could be doing on a Sunday morning."
    -Bill Gates

  5. #5
    Join Date
    Apr 2007
    Beans
    14,781

    Re: [Python] Print matching lines in a file

    Quote Originally Posted by Can+~ View Post
    Right, I always forget the in operator.
    It is handy

    It is also faster I think.

  6. #6
    Join Date
    Nov 2005
    Location
    Leeds, UK
    Beans
    1,634
    Distro
    Ubuntu Development Release

    Re: [Python] Print matching lines in a file

    Thanks both of you! I used LaRoza's method because it was a lot simpler. I thought I tried that yesterday but my IDE froze for a while. I think I know why. It outputs a lot very quickly so redrawing everything uses up the cpu completely.

    One more question, what is the preferred way of outputting to a text file and would it work on every platform? At the moment I'm using print:

    Code:
    print >> file, "string"
    but I get IOError: [Errno 2] No such file or directory if the file doesn't exist. Is there the equivalent of unix touch in python? (has to be cross platform)

    Thanks again.

  7. #7
    Join Date
    Feb 2007
    Beans
    4,045
    Distro
    Ubuntu 9.10 Karmic Koala

    Re: [Python] Print matching lines in a file

    You need to open the file in write or append mode. help(file)
    Code:
    f= file("/tmp/foo.txt", "w")
    print >> f, "something"
    f.close()

  8. #8
    Join Date
    Nov 2005
    Location
    Leeds, UK
    Beans
    1,634
    Distro
    Ubuntu Development Release

    Re: [Python] Print matching lines in a file

    Okie, I was using r+ instead of w, maybe that was my problem....Thanks.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •