views:

52

answers:

1

I am using code below. How Do add error checking. If anything is error, replace continue reading Ex: if volume is N\a or missing , replace with 'a value.' Don't skip line, don't stop.

reader = csv.reader(idata.split("\r\n"))

stocks = []
for line in reader:
    if line == '':
        continue

    stock, price, volume, stime = line
    price = float(price)
    volume = int(volume)

    stocks.append((stock, price, volume, stime))
+2  A: 

Do something like the following:

def isRecordValid(stock,price,volume,stime):
    #do input validation here, return True if record is fine, False if not.  Optionally raise an Error here and catch it in your loop
    return True

reader = csv.reader(idata.split("\r\n"))

stocks = []
for line in reader:
    if line == '':
        continue

    stock, price, volume, stime = line
    try:
        if isRecordValid(stock,price,volume,stime):
            price = float(price)
            volume = int(volume)
            stocks.append((stock, price, volume, stime))
        except Exception as e:
            print "either print or log and error here, using 'except' means you can continue execution without the exception terminating your current stack frame and being thrown further up"

Basically define another method (or do it inline) to validate that stock, price, volume, and stime are all as you expect it. I'd try to catch any Errors here too in case your float() or int() calls to convert the price and volume strings to their expected types fails for whatever reason.

whaley
thanks! My thoughts were only a few records will be bad, or error. I was thinking some like if volume is text, return int(0), if price is text, return float(0)