user2242044
user2242044

Reputation: 9213

Python if statement using CSV Data

I am reading in some data from a CSV file and then printing a value based on an if statement, but it doesn't seem to make sense to me. I would expect it would print equal to 1

PYTHON CODE:

import csv

#open CSV file
csvfile = open("C:\\python.csv", "rb")
data = csv.reader(csvfile)
data = [row for row in data]

#start loop through each item
for currentrow in range(1, 2):  # numbers off due to array starting at 0
    #grab one record data [row][col]
    Count = data[currentrow][7]

    print "Count equals: " + Count

    if Count > 1:
        print "greater than 1"
    if Count == 1:
        print 'equal to 1'

OUTPUT:

Count equals: 1.00
greater than 1

Upvotes: 1

Views: 5771

Answers (1)

inspectorG4dget
inspectorG4dget

Reputation: 113915

Your trouble stems from the fact that what you read from a file is always a string (i.e. str type). This means that even if the file contains a number, it is read into your variable as a string. Therefore, if your file looks like this:

myFile.txt:

2

And if you did:

with open('myFile.txt') as infile:
    x = infile.readline()

then, x would have the value '2', which is a str type. This means, that if you did x*2, you'd get '22', because that's how strings multiply out.

What you really want, is to convert that sting into an int. This is called "casting a string into an integer" and can be done very simply:

y = int(x)

There's another type that you should be aware of: float. It is used to hold decimal numbers. So, if you were to say

x = 3.4

then x would be a float. You can also cast ints to floats:

z = float(y)

would turn z into a float, with the value 2.0

Now, onto your actual problem:

data = [row for row in data]  # data is now a list of lists; each sublist is a list of strings
for currentrow in range(1,2):
    Count = data[currentrow][7]  # Count is now the string at index 7, of the sublist at index `currentrow`, i.e. 1.00
    Count = float(Count)  # Count is now the floating point value of the string '1.00'
    Count = int(Count)  # Count is now the integer value of 1.00, i.e. 1
    if Count > 1:
        print "greater than 1"
    if Count == 1:
        print "equal to 1"

Now, onto your second problem:

print 'Count equals ' + Count

Here, you are trying to add a str and an int. Well, those are incompatible types for addition. Therefore, you should cast the int into a str; and just like how strs can be cast into ints, ints can be cast into strs with a call to str():

Count_str = str(Count)

So when you want to print the value, you could do:

print "Count equals " + str(Count)

Of course, the print statement is a little more friendly and lets you do something like this:

print "Count equals", Count  # no casting needed here

Upvotes: 3

Related Questions