Matt
Matt

Reputation: 15

How to find if any element within a list is present within a row in a CSV file when using a for loop

import csv

with open('example.csv', 'r') as f:
    csvfile = csv.reader(f, delimiter = ',')

    client_email = ['@example.co.uk', '@moreexamples.com', 'lastexample.com']

    for row in csvfile:
        if row not in client_email:
            print row

Assume code is formatted in blocks properly, it's not translating properly when I copy paste. I've created a list of company email domain names (as seen in the example), and I've created a loop to print out every row in my CSV that is not present in the list. Other columns in the CSV file include first name, second name, company name etc. so it is not limited to only emails.

Problem is when Im testing, it is printing off rows with the emails in the list i.e [email protected].

Any ideas?

Upvotes: 1

Views: 933

Answers (3)

Allan
Allan

Reputation: 11

In your example, row refers to a list of strings. So each row is ['First name', 'Second name', 'Company Name'] etc.

You're currently checking whether any column is exactly one of the elements in your client_email.

I suspect you want to check whether the text of any column contains one of the elements in client_email.

You could use another loop:

for row in csvfile:
    for column in row:
        # check if the column contains any of the email domains here
        # if it does:
            print row
            continue

To check if a string contains any strings in another list, I often find this approach useful:

s = "xxabcxx"
stop_list = ["abc", "def", "ghi"]
if any(elem in s for elem in stop_list):
    pass

Upvotes: 1

Reck
Reck

Reputation: 1436

Another possible way,

import csv

data = csv.reader(open('example.csv', 'r'))
emails = {'@example.co.uk', '@moreexamples.com', 'lastexample.com'}
for row in data:
    if any(email in cell for cell in row for email in emails):
        print(row)

Upvotes: 0

niraj
niraj

Reputation: 18208

One way to check may be to see if set of client_email and set in row has common elements (by changing if condition in loop):

import csv

with open('example.csv', 'r') as f:
    csvfile = csv.reader(f, delimiter = ',')

    client_email = ['@example.co.uk', '@moreexamples.com', 'lastexample.com']

    for row in csvfile:
        if (set(row) & set(client_email)):
            print (row)

You can also use any as following:

import csv

with open('untitled.csv', 'r') as f:
    csvfile = csv.reader(f, delimiter = ',')

    client_email = ['@example.co.uk', '@moreexamples.com', 'lastexample.com']

    for row in csvfile:
        if any(item in row for item in client_email):
            print (row)

Upvotes: 0

Related Questions