how to discard a line if it's not a number?

Discussion in 'Python' started by dawenliu@gmail.com, Oct 29, 2005.

  1. Guest

    Hi, I'm reading a file line by line, and whenever a line is not
    consisted of a single number (such as 0.315), I want to discard that
    line (and store only the single numbers).

    For example,

    0.315
    discarded this line of text
    3.8
    -1.44
    forget about me also
    2.6


    Then I want to store only the four numbers into another file, without
    the two sentences.
    Suggestions are appreciated!
    , Oct 29, 2005
    #1
    1. Advertising

  2. Guest

    This is a possible solution, using exceptions:

    fileName = "data"
    out = file(fileName + "_filt.txt", "w")
    for line in file(fileName + ".txt"):
    try:
    nline = float(line)
    except ValueError:
    pass
    else:
    out.write(str(nline) + "\n")
    out.close()

    If the file is small enough this can be a little faster:

    fileName = "data"
    filtered = []
    data = file(fileName + ".txt").readlines()
    for line in data:
    try:
    filtered.append( str(float(line)) )
    except ValueError:
    pass
    out = open(fileName + "_filt.txt", "w")
    out.write( "\n".join(filtered) )
    out.close()

    Bye,
    bearophile
    , Oct 29, 2005
    #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. David Smith
    Replies:
    2
    Views:
    369
    Shane Petroff
    Jul 24, 2003
  2. Leif K-Brooks
    Replies:
    5
    Views:
    325
    David Fraser
    Apr 15, 2005
  3. gobis
    Replies:
    4
    Views:
    496
  4. Covington Bradshaw

    Servlets / How can we discard a request?

    Covington Bradshaw, Mar 10, 2007, in forum: Java
    Replies:
    7
    Views:
    905
    Chris Uppal
    Mar 12, 2007
  5. Jim

    Discard qualifiers

    Jim, Aug 24, 2007, in forum: C++
    Replies:
    2
    Views:
    1,039
    Rolf Magnus
    Aug 24, 2007
Loading...

Share This Page