0

I have a file containing these contents:

123.123
456.456
789.789

Added up, they should give 1369.368.

I'm trying to read these numbers from the file and add them up, but I have no idea how.

I have this code so far:

with open("tmpscore.txt") as tmp:
numbers = tmp.read().splitlines()

This prints ['123.123', '456.456', '789.789'] - one step closer. (Reason I need to do that is because another file writes them, and I need to get rid of the "/n"s.)

I could just use something like this:

with open("tmpscore.txt") as tmp:
numbers = tmp.read().splitlines()

a, b, c = numbers[0], numbers[1], numbers[2]
a, b, c = float(a), float(b), float(c)

print(a+b+c)

This would work, but my issue is this is actually a small test program for a larger program, that will work on the same principle (gathering numbers from a file, adding them up, like that does), but the issue is the other program has to deal with a lot more than 3 numbers. Currently there'd be 20 or so lines in that file, and I don't want to write a, b, c, d, e, f = etc etc etc, because that's both inefficient and time consuming.

4
  • Use sum to calculate the sum of floats in the list.
    – vaultah
    Jan 24, 2016 at 16:44
  • Read the lines with nums = f.readlines() after opening the file and then sum them with sum(float(n) for n in nums). Jan 24, 2016 at 16:47
  • 1
    Actually, float ignores whitespace. There's no need for explicit strip call. @Jim
    – vaultah
    Jan 24, 2016 at 16:50
  • @vaultah wasn't aware of that, cheers. Jan 24, 2016 at 16:51

0

Browse other questions tagged or ask your own question.