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

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sat Oct 29 22:50:00 CEST 2005


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




More information about the Python-list mailing list