Get String Type Data from a CSV Document

Asked

Viewed 83 times

2

I have a CSV (Excel) document with valid and invalid emails. And I wanted to take 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 the results to appear only '[email protected]' without the '[]', so I can validate them.

  • You can just ', '.join(ifile.read().splitlines()), you get, "Email1, Email2, email3, ..."

1 answer

2


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

for row in read: ...

will be a list of all found columns. As your file has only one column with the email, the value of row will be a list with an element. When doing csvArray.append(row) you add the entire list in 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 on Repl.it

But one more solution pythonica 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 on Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.