1

If I print a row in a CSV I get this result:

,,,,,,,some text,1781786000,

How can I check if an element row[2] has value?Is this correct if I check if element row[2] is empty:

if row[2] =! '':
    print row[2]

or

  if row[2] =! None:
        print row[2]

How can I check if any of elements for row[0] till row[5] have no value so they are just ,, ?

let's suppose that in row[0:6] there's only one element that has a value others are empty, how can I make a condition that checks which element from row[0:6] has value?

4
  • change or to and if row[2] =! '' and row[2] != None: since both condition are falsy values you could do if row[2] Commented Dec 21, 2015 at 13:41
  • Actually i want to know which condition should i use? @ Vignesh Kalai Commented Dec 21, 2015 at 13:44
  • Can't you just use if row[2] Commented Dec 21, 2015 at 13:44
  • =! is a SyntaxError. Use a loop to check all columns, or use the any function. Commented Dec 21, 2015 at 13:50

3 Answers 3

5

The "Pythonic" way of doing this is to simply say:

if row[2]:
    print row[2]

This works because both None and '' would be interpreted as False-y values and the condition for the if would not be satisfied.

Sign up to request clarification or add additional context in comments.

Comments

0

if you want to check if any element in the row have some value you can do

if any(row[0:6])

to know witch one you can do a filter and combined it with a enumerate to know its position like this

for i, value in filter(lambda pair: pair[1],enumerate(row[0:6])):
    do something...

that is functional style of writhing this

for i,value in enumerate(row[0:6]):
    if value:
        do something ...

Comments

0

I'd do:

with open('csv_file.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:
        if not row[2]:
            continue  # this will skip to the next for loop iteration
        # do your processing here

Comments

Your Answer

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