Lance Hietpas Lance Hietpas - 1 year ago 174
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 Source

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())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download