I'm new to python and writing a program to count lines. the file looks like this:
0.86149806
1.8628227
-0.1380086
-1
0.99927421
-1.0007207
0.99927421
0.99926955
-1.0007258
And my code attempt is the following:
counterPos = 0
counterNeg = 0
counterTot = 0
counterNeu = 0
with open('test.txt', 'r') as infile:
for line in infile:
counterTot += 1
for i in line:
if i > 0.3:
counterPos += 1
elif i < -0.3:
counterNeg += 1
else:
counterNeu += 1
I'm trying to get it to count all lines lower than -0.3 to counterNeg, all lines above 0.3 as counterPos, and all lines that have a number between 0.29 and -0.29 to counterNeu.
It doesn't seem to work though, I know im going wrong with for i in line but not sure how.
Your line is a string, but you want to parse it as a float. Just use float(line).
It's also better to strip all whitespace from the beginning and end of your line just in case. So:
for line in infile:
i = float(line.strip())
# ... count
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With