Lance Hietpas Lance Hietpas - 2 months ago 25
Python Question

Python CSV Splitting Full Name String into First and Last Name

I have a .csv that has a full name column with around 50 first and last names. I would like to use Python to import the .csv and loop thru and split the full name into first and last name columns into a new .csv file. I am not sure how to go about this with Python.

Answer

Here is some code that will help you, you can use the csv module as others have suggested in the comments

import csv

with open('old.csv', 'rb') as f:
    reader = csv.reader(f)
    newcsvdict = {"first name": [], "last name": []}
    for row in reader:
        first = row[0].split()[0]
        last = row[0].split()[1]
        newcsv["first name"].append(first)
        newcsv["last name"].append(last)

with open('new.csv', 'wb') as f:
    w = csv.DictWriter(f, newcsvdict.keys())
    w.writeheader()
    w.writerows(newcsvdict)