By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,767 Members | 1,995 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,767 IT Pros & Developers. It's quick & easy.

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

P: n/a
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 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.