[Tutor] Python 3: string to decimal conversion

Saidov usaidov at gmail.com
Sat May 21 14:34:20 EDT 2016


Hello all,

I am working on a piece of python code that's supposed to help me manage a
budget:

1. Read a banking statement
2. Categorize expenses and income by month and by type
3. Print out a report comparing the projected expenses/income with actual
numbers.

*File characteristics:*
Banking statement in a csv file format.
contents: 5 columns, 1st column= date, 4 column=expenses
date format: mm/dd/yyyy, type: string
expenses format: ($0.00), type: string
income format: $0.00, type: string


*Python Version: 3.5 (64 bit)*
IDE:Microsoft Visual Studio Community 2015
Version 14.0.25123.00 Update 2

Python Tools for Visual Studio   2.2.40315.00
Python Tools for Visual Studio provides IntelliSense, projects, templates,
Interactive windows, and other support for Python developers.


*Problem:*
 I want to convert expense/income values into a decimal form so I could sum
them into appropriate buckets according to the month in which they occur. I
am getting the following error message when I run my code:

"decimal.InvalidOperation was unhandled by user code
Message: [<class 'decimal.ConversionSyntax'>]"

*Question: *I tried looking up the meaning of this error, but couldn't find
anything on the internet. *Can someone help me understand what's wrong with
my code?*

Below is my code:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import numpy as np
import csv
import timestring as ts
import decimal

months= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
expenses = {x: decimal.Decimal() for x in months}
income = {x: decimal.Decimal() for x in months}

exp_cat = []
income_cat = []

files =['export.csv']

with open("budgetfile.csv","wt") as fw:
    writer = csv.writer(fw)
    for file in files:
        with open(file) as csvfile:
            records = csv.reader(csvfile, quoting=csv.QUOTE_NONE)
            print("Processing file {}. \n" .format(file))
            header = next(records)
            for row in records:
                row[4].replace("($","")
                row[4].replace(")","")
                row[4].replace('"', '')

                try:
                    expenses[ts.Date(row[0]).month] +=
decimal.Decimal(row[4])

                except ValueError:
                    pass
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


More information about the Tutor mailing list