0

Suppose I have a csv file looks like:

(a,3,,,,)
(b,,,,,)
(c,2,,,,)
(d,,,,,)
(e,,,,,)
(f,1,,,,)
(g,,,,,)

I am trying to find out which alphabet (i.e a,b,c,d,e,f,g) has a value in column (let's say column 1 here).
The code I've written is here:

set3 = set([n[column] for n in new_marks])

if set3 != '':

      print
      print '{0} is not empty'.format(list(set3))

This code only prints value in column 1 not alphabets...

Can anyone help me with figuring out this problem?

Thank you

1
  • 1
    set3, being a set, is never going to equal the empty string. Commented Aug 26, 2012 at 12:07

7 Answers 7

2

I would do something similar to:

import csv

def strip_bits(obj):
    for el in obj:
        yield el[1:-2]

with open('/home/jon/testfile.csv') as fin:
    tempin = strip_bits(fin)
    csvin = csv.reader(tempin)
    for row in csvin:
        if any(row[1:]):
            print row[0] # or do whatever
Sign up to request clarification or add additional context in comments.

Comments

1

without csv solution:

with open('data.txt') as f:
    for x in f:
        x=x.strip().strip('()')
        spl=x.split(',')
        if spl[0] in ('a','b','c','d','e','f','g') and spl[1]!='':  #replace spl[1] with
                          # any other column if you want to find value in some other column
            print ("{0} is not empty".format(spl[0]))

output:

a is not empty
c is not empty
f is not empty

Comments

0
d = dict((n[0], n[column]) for n in new_marks)
if d:
    print
    print '{0} is not empty'.format(d.keys())

Comments

0

Modify the first line:

set3 = set([n[0] for n in new_marks if n[column] is not None])

Comments

0

this code does pretty much what i understand from your question.

i am not sure what you define as a "value" so here it is simply any row that has more than 1 column. but this code can be easily modified.

#holds the rows from the file
rows = []
#opens and reads each row of the file (CSVFILE = full file location)
with open(CSVFILE, "r") as CSV_read:
    next(CSV_read) # removes headers/colum names (if you dont have any - remove this line)
    for line in CSV_read:
        #cleans and splits the line into colums
        vals = line.strip("\r\n").strip("\n").split(",")
        #adds the line to the list of rows
        rows.append(vals)

#holds the alphabet (first colum value) of each row that has more values/cells
have_value = []
#goes over each row in the rows
for row in rows:
    #if there are any values after the initial 'alphabet'
    if len(row) > 1:
        # add to the list of things with values.
        have_value.append(row[0])

Comments

0

How about this?

s = """a,3,,,,
b,,,,,
c,2,,,,
d,,,,,
e,,,,,
f,1,,,,
g,,,,,"""
buf = StringIO(s)
d = {}
for row in csv.reader(buf,delimiter=','):
  d[row[0]] = row[1:]

looking_for = 2

for alpha,items in d.iteritems():
   try:
       if items[looking_for-1] == '1':
           print 'Letter %s has value in column %s' % (alpha,looking_for)
   except IndexError:
       print "List doesn't contain %s columns!" % looking_for

Comments

0

A CSV is nothing but a pure comma-seperated text file, isn't it ?

with open("/path/to/myfile.csv") as f:
    for line in f:
        line_chars = line.strip()[1:-1].split(",")
        k, v= line_chars[0], "".join(line_chars[1:])
        if v: print k, v

2 Comments

A CSV file may have the comma delimiter inside quotes, which makes it part of a column content, rather than a separator... So as much as it's lovely to be to (sometimes) purely split on a string, you can't...
@Jon, Right, I just forgot that. Thank you for pointing it out. If in Keww's case there are only integers(as his sample shows), my code still can work though ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.