Mahsolid Mahsolid - 6 months ago 68
Python Question

Python - loop through a csv file row values

I have a csv file like the following (test.csv) with two columns.

338,800
338,550
339,670
340,600
327,500
301,430
299,350
284,339
284,338
283,335
283,330
283,310
282,310
282,300
282,300
283,290


From column 1, I wanted to read current row and compare it with the value of the previous row. If it is
greater
OR
equal
, continue comparing and if the value of the current cell is
smaller
than the previous row - then i wanted to the value of the second column in the same row.

Next I wanted to divided the
larger value
we got in column 1 by the value in the same cell of column two. Let me make it clear.

For example in the table given above: the smaller value we will get depending on my requirement from Column 1 is 327 (because 327 is smaller than the previous value 340) - and then we take 500 (which is the corresponding cell value on column 2). Finally we divide 340 by 500 and get the value 0.68. My
python
script should exit right after we print the value to the console.

Currently, I am using the following script in bash, and it works fine

awk -F, '$1<p && $2!=0{
val=$2/p
if(val>=0.8 && val<=0.9)
{
print "A"
}
else if(val==0.7)
{
print "B"
}
else if(val>=0.5 && val <0.7)
{
print "C"

}
else if(val==0.5)
{
print "E"
}
else
{
print "D"
}
exit
}
{
p=$1
}' test.csv


but I wanted to do it with
python
and i would appreciate for any help. Here is my approach

import csv

f = open("test.csv", "r+")
ff = csv.reader(f)

previous_line = ff.next()
while(True):
try:
current_line = ff.next()
if previous_line <= current_line:
print "smaller value"
except StopIteration:
break

Answer Source

I recommend you use csv.Reader's built-in iteration rather than calling .next() directly. And your code should not test normal floats for equality. In any language, that's not just a Python thing. Also, a calculated value of 0.79 will result in D which may not be what you intend.

from __future__ import division
import csv

def category(val):
    if 0.8 < val <= 0.9:
        return "A"
    #Note: don't test val == 0.7: you should never test floats for equality
    if abs(val - 0.7) < 1e-10:
        return "B"
    if 0.5 < val < 0.7:
        return "C"
    if abs(val - 0.5) < 1e-10:
        return "E"
    return "D"

with open(r"E:\...\test.csv", "r") as csvfile:
    ff = csv.reader(csvfile)

    previous_value = 0
    for col1, col2 in ff:
        if not col1.isdigit():
            continue
        value = int(col1)
        if value >= previous_value:
            previous_value = value
            continue
        else:
            result = previous_value / int(col2)
            print category(result)
            break