I am trying to write a simple program that should give the following output when it reads csv file which contains several email ids.
email_id = ['emailid1@xyz.com','emailid2@xyz.com','emailid3@xyz.com'] #required format
but the problem is the output I got is like this following:
[['emailid1@xyz.com']]
[['emailid1@xyz.com'], ['emailid2@xyz.com']]
[['emailid1@xyz.com'], ['emailid2@xyz.com'], ['emailid3@xyz.com']] #getting this wrong format
here is my piece of code that I have written: Kindly suggest me the correction in the following piece of code which would give me the required format. Thanks in advance.
import csv
email_id = []
with open('contacts1.csv', 'r') as file:
reader = csv.reader(file, delimiter = ',')
for row in reader:
email_id.append(row)
print(email_id)
NB.: Note my csv contains only one column that has email ids and has no header. I also tried the email_id.extend(row)
but It did not work also.
You need to move your print
outside the loop:
with open('contacts1.csv', 'r') as file:
reader = csv.reader(file, delimiter = ',')
for row in reader:
email_id.append(row)
print(sum(email_id, []))
The loop can also be like this (if you only need one column from the csv):
for row in reader:
email_id.append(row[0])
print(email_id)