brohjoe brohjoe - 3 months ago 7x
Python Question

decimal.Decimal is not iterable error

I have a simple script that takes a list containing 3 columns of data. The second column of data contains currency values with a leading dollar sign. I have stripped away the dollar sign from the second column, now I need to add up the values. I'm getting a "decimal.Decimal is not iterable" error. Here is the code:

from decimal import Decimal

def main():
total = 0.0

infile = open('list.txt', 'r')

for i in infile:
parts = i.split()
if len(parts) > 1:
dollar_dec = Decimal((parts[1]).strip('$'))
total = sum(dollar_dec)
print (total)


except Exception as err:



Say, you have the following file content:

content = """\
one $1.50
two $3.00
three $4.50"""

You can use the in-place operator += to calculate the total:

from decimal import Decimal
import io

total = Decimal(0)
with io.StringIO(content) as fd:
    for line in fd:
        parts = line.strip().split()
        if len(parts) > 1:
            dollard_dec = Decimal(parts[1].strip("$"))
            total += dollard_dec


Her, you get: 9.00

You can also use sum() on a iterable (here a comprehension list):

with io.StringIO(content) as fd:
    total = sum(Decimal(line.strip().split()[1].strip("$"))
                for line in fd)

Yes, you get 9.00 too!