Get String data from a CSV document

2

I have a CSV (Excel) document with valid and invalid emails. And I wanted to get the values of the fields in the form of string , but the following code gives the return shown below:

import csv
import re

ifile  = open('ead.csv', "r")
read = csv.reader(ifile, delimiter=' ', quotechar='|')
csvArray = []

for row in read : 
    csvArray.append(row)
print(csvArray[0:10])

Return:

[['[email protected]'], ['[email protected]'], ['[email protected]'], ['[email protected]'], ['[email protected]'], ['[email protected]'], ['[email protected]'], ['[email protected]'], ['[email protected]'], ['[email protected]']]
>>> 

But I need results to appear only '[email protected]' without '[]' , so I can validate them.

    
asked by anonymous 03.04.2018 / 20:15

1 answer

2

When you read a CSV file, the row object in:

for row in read: ...

will be a list with all the columns found. Since your file has only one column with the email, the value of row will be a list with one element. When you do csvArray.append(row) you add the whole list to csvArray and not just the value of the email. Knowing that will always be the first column the email, could do:

import csv
import re

ifile  = open('ead.csv', "r")
read = csv.reader(ifile, delimiter=' ', quotechar='|')
csvArray = []

for row in read : 
    csvArray.append(row[0])
print(csvArray[0:10])

See working at Repl.it

But a more pythonica solution for your problem would be:

import csv

def get_emails_from_csv(filename):
    with open(filename) as stream:
        reader = csv.reader(stream, delimiter=' ', quotechar='|')
        for line in reader:
            yield line[0]

emails = get_emails_from_csv('ead.csv')

print( list(emails) )

See working at Repl.it

    
04.04.2018 / 13:51