1

if I have a file which contains

  • 10,20,,30
  • 10,20,5,20
  • 3,20,19,50
  • 10,20,10,30

how to get the sum of each line and ignore that the first line has a blank element

this is what I've got, but it only gives me this error message

TypeError: unsupported operand type(s) for +: 'int' and 'str'

file = open(inputFile, 'r')

for line in file:
    result = sum(line)
    print(result)
Keric Ma
  • 17
  • 5
  • 3
    Possible duplicate of [Sum a list of numbers in Python](https://stackoverflow.com/questions/4362586/sum-a-list-of-numbers-in-python) – Mocking Jul 28 '18 at 00:29

3 Answers3

0

Version 1:

with open("input.txt") as f:
    for line in f:
        result = sum(int(x or 0) for x in line.split(",")) 
        print(result)

This handles the empty string case (since int("" or 0) == int(0) == 0), and is fairly short, but is otherwise not exceedingly robust.

Version 2:

with open("input.txt") as f:
    for line in f:
        total = 0
        for item in line.split(","):
            try:
                total += int(item)
            except ValueError:
                pass
        print(total)

This is more robust to malformed inputs (it will skip all invalid items rather than throwing an exception). This may be useful if you're parsing messy (e.g. hand-entered) data.

Ollin Boer Bohan
  • 2,296
  • 1
  • 8
  • 12
0

It's not working because you try to sum string like this

'10,20,,30'

or this

'10,20,5,20'

My solution:

import re

regex = re.compile(r',,|,')

with open(file, 'r') as f:
    for line in f:
        s = 0
        for x in regex.split(line):
            s += int(x)
        print(s)
ZRTSIM
  • 75
  • 6
0

My code looks stupid, but it works, you can found another way, let the codes looks more smart and professional.

def my_function():
  file = open("exampleValues","r")
  total = 0
  for line in file:
      a,b,c,d=line.split(",")
      if a=='':
          a=0
      if b=='':
          b=0
      if c=='':
          c=0
      if d=='':
          d=0
      a=int(a)
      b = int(b)
      c = int(c)
      d = int(d)
      print(a+b+c+d)
my_function()
Jack Chen
  • 66
  • 3