[Tutor] Using if statement with csv file

Matthew Ruffalo mmr15 at case.edu
Tue Jan 27 19:15:00 CET 2015

On 01/27/2015 08:04 AM, Tammy Miller 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.Thank you, Tammy

Hi Tammy-

A few things:

1. Indentation is semantically significant in Python programs, so please
send mail in a way that doesn't collapse all of your code to a single
line. I assume this is an appropriate reconstruction (though note that
you are missing a colon after "if row['Absent'] > 10" and I have added
this in my version):

import csv
with open('test.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row['Absent'] > 10:
            print row

2. Please state the operating system and version of Python you are
using. In this case it's clear that you are using Python 2.x from the
'print' statement, and operating system is not relevant, but this is not
always the case and it's best to not have to guess about how to help you.

In this case, since it's clear that you're using Python 2, you're
encountering some suboptimal behavior that was fixed in Python 3.
Specifically, you're not converting row['Absent'] into an integer and
strings always compare greater than integers:

Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> '5' > 10
>>> '' > 3

In Python 3, this meaningless comparison raises a TypeError:

Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> '5' > 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

It will probably suffice to change your "if row['Absent'] > 10" to "if
int(row['Absent']) > 10".


More information about the Tutor mailing list