Search code examples
pythonpython-3.xcsvmultiple-value

how to read multiple values from a field in csv file using python 3


Hi I have a csv file delimited by comma like this.

name, email1; Email2; email3, etc, telephone

I want to extract all the emails addresses from the email field using csv module in python. And from each email address write a row using the other fields like this

name, email1, etc, telephone
name, Email2, etc, telephone
name, email3, etc, telephone

Maybe I need to read the email field and split it in separated strings?


Solution

  • Create a CSV reader and writer, and as you said, read the file using the standard , separator, and then split the email field manually using ;. For each email entry, write the other fields:

    import csv
    
    with open('input.csv', newline='') as f_input, open('output.csv', 'w', newline='') as f_output:
        csv_input = csv.reader(f_input)
        csv_output = csv.writer(f_output)
    
        for row in csv_input:
            emails = row[1].split(';')
            for email in emails:
                csv_output.writerow([row[0], email]  + row[3:])
    

    Or slightly more compact as:

    import csv
    
    with open('input.csv', newline='') as f_input, open('output.csv', 'w', newline='') as f_output:
        csv_output = csv.writer(f_output)
    
        for row in csv.reader(f_input):
            csv_output.writerows([row[0], email] + row[3:] for email in row[1].split(';'))
    

    Tested using Python 3.x