[Tutor] Using if statement with csv file

Danny Yoo dyoo at hashcollision.org
Tue Jan 27 19:20:59 CET 2015


On Tue, Jan 27, 2015 at 5:04 AM, Tammy Miller <tgmiller5 at hotmail.com> wrote:
> I have a csv file. I would like to create a filter or if statement on a column but it is not producing the right results. It displays everythingHere is the example:import csvwith open('test.csv') as csvfile:    reader = csv.DictReader(csvfile)for row in reader:    if row['Absent'] > 10      print rowI just want the column Absent to show me all of the numbers that are greater than 10.  It gives me all the results.  I am not sure what to do.

Hi Tammy,

Ah.  Take a look at the following:

########################
>>> 'foo' > 10
True
########################

Waaaaaa?  What does it even mean to compare a string to a number?


It turns out that Python's comparison operator decides that if we're
comparing a string vs a number, the string is "bigger", regardless of
its content.

(Reference: https://docs.python.org/2/library/stdtypes.html#comparisons.)


Now take a look at this:

########################
>>> '10' > 10
True
########################

Waaaaaaa?  But yes, it's doing this for the same reasons as before: a
string is just bigger than a number.



In your code, you are comparing a string (an element of your CSV row)
with a number.


Hope this helps!


More information about the Tutor mailing list