1

I am trying to read a file using csv.DictReader

I have a field that is supposed to be an integer.if it is empty i will set it as DEFAULT if it is an integer i do nothing.if it is not an integer i check if it is a quoted integer(like '1234').if so I will convert it to integer.Else an exception is raised.

it works as expected if its empty or it is an integer.Now if it is a quoted integer(like '1234') ,an exception is raised integer invalid literal for float(): '1234'.

it is not supposed to raise exception in this case.

I think it has something to do with the way DictReader reads the csv file. Everyhting else is just fine.Please help

 if not line[key]:
    line[key]='DEFAULT'
 elif not isinstance(line[key], (int, long, float)) :                        
    try:
      line[key]=float(line[key])
    except Exception,e :
      print e
2
  • What version of Python are you using? float() should work just fine on strings. However, if all the numbers are integers, why not use int(). Commented Jul 28, 2011 at 13:50
  • By integer i meant numeric.sorry.Also aix's answer is correct.its just that I cannot accept an answer within 8 minutes Commented Jul 28, 2011 at 13:55

3 Answers 3

4

The problem is that the single quotes are part of your string:

In [7]: float("'1234'")
ValueError: invalid literal for float(): '1234'

If you remove them, things should work:

In [8]: float("'1234'".strip("'"))
Out[9]: 1234.0
Sign up to request clarification or add additional context in comments.

Comments

1

This might not be the smartest way, but if you want to make sure there are only digits in your string, you could just remove all non-digits.

>>> import string
>>> extract = lambda s, charset: "".join(c for c in s if c in charset)
>>> float( extract("'h0424.234\"foo", string.digits + ".") )
424.234

Comments

0

If your literal is something like "'1234'" or '"1234"' and '1234' you can use replace before converting:

data = ["'1234'", '"1234"', '1234', '', 1234]
[float(str(a).replace("'","").replace('"','')) if str(a).strip() else 'DEFAULT' for a in data]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.