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))
Carl Manaster
40.5k17 gold badges109 silver badges158 bronze badges
asked Sep 7, 2010 at 16:02
Merlin
25.8k44 gold badges141 silver badges213 bronze badges
1 Answer 1
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.
answered Sep 7, 2010 at 16:13
whaley
16.3k10 gold badges61 silver badges68 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Merlin
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)
lang-py