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

D

dawenliu

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!
 
B

bearophileHUGS

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top