How do you write a python code that looks at a specific cell in a csv file?
I have the following data in a csv file
1 0 100
2 11 150
3 0 189
4 0 195
5 21 245
I need to write a program in python that will count the number of non zero values in the SECOND column only. Any hints? All help is greatly appreciated.

Recommended Answers

All 3 Replies

Hello machine91!

Take a look at python's "csv" module. I believe it will give you what you need.

I'm a python noob, but here's a basic example that does something close to what I think you're looking for:

#!/usr/bin/python

import csv

csvInput = csv.reader(open('test.txt', 'rb'), delimiter=' ')
count = 0

for row in csvInput:
    print row[1],
    if row[1] != "0":
        print "non-zero!"
        count += 1
    else:
        print

print "Non-zero total: %s" % count

I hope this helps!
-G

Thank you for your help, you have certainly provided me with some ideas. Although the code I have now tried keeps giving me the error 'IndexError: list index out of range' Any ideas on what this error means and how I could solve it? Thanks again. :)

Interesting! One way I was able to reproduce that is with an extra line at the end of the input file. Here's a successful run:

-> cat -E test.txt 
1 0 100$
2 11 150$
3 0 189$
4 0 195$
5 21 245$

-> python test.py 
0
11 non-zero!
0
0
21 non-zero!
Non-zero total: 2

Here's a run with an extra line at the end of the csv file:

-> echo >> test.txt

-> cat -E test.txt 
1 0 100$
2 11 150$
3 0 189$
4 0 195$
5 21 245$
$

-> python test.py 
0
11 non-zero!
0
0
21 non-zero!
Traceback (most recent call last):
  File "test.py", line 9, in ?
    print row[1],
IndexError: list index out of range

So you might want to look at a way to check the input and trim out any blank lines, if there are any. It could also be something else entirely!...

Here's a simple example that checks to see if the list is empty before trying to process it:

#!/usr/bin/python
 
import csv
 
csvInput = csv.reader(open('test.txt', 'rb'), delimiter=' ')
count = 0
 
for row in csvInput:
    if row:
        print row[1],
        if row[1] != "0":
            print "non-zero!"
            count += 1
        else:
            print
 
print "Non-zero total: %s" % count

Again, I'm terrible at python, but I hope this helps! :)
-G

commented: nice effort +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.