Ted Heath
Ted Heath

Reputation: 380

python filter csv row

Ive a csv file . Im trying to check each row by 2 variables.

 csv:
 1,2
 1,3
 2,3
 3,2
 8,5

script:

 import csv
 a= 2
 b= 3

 with open('ondo.csv','r') as rows1:
 for row in rows1: 
         if (str(a) and str(b)) in row:
            print ('oops')
         else:
            print (row)

Produces

1,2

oops
oops
oops
8,5

2 and 3 are supposed to be found in 2 rows only . Whats the right way to filter and what causes the newline in shell.

Upvotes: 0

Views: 161

Answers (1)

cco
cco

Reputation: 6281

[[ NB: I'm assuming that for row in rows1: should be indented another level ]]

The problem is that (str(a) and str(b)) evaluates to '3', so if (str(a) and str(b)) in row: is the same as if '3' in row:.
The first row (1, 2) doesn't contain '3', so it is printed (including it's attached newline and one from print for free). The last line (8, 5) also does not contain '3', so it is printed. Either the file does not end in a newline, or you didn't notice the blank line at the end of the output.

The condition you want is:

if str(a) in row and str(b) in row:

but that's really not the best way to do this, since it would be True for a line that has 23 in it (the CSV module is your friend here). There is also no reason not to define a and b as '2' and '3', since you only use them as strings.

Upvotes: 1

Related Questions