Last active
January 1, 2023 21:10
-
-
Save larrasket/9a8a8263955351eb5c20a02bda7880bd to your computer and use it in GitHub Desktop.
Python script to split full name column in csv to first and last name columns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import sys | |
# Get the filename from the command line arguments | |
filename = sys.argv[1] | |
# Open the file in read mode | |
with open(filename, 'r') as csv_file: | |
# Read the file into a CSV reader object | |
reader = csv.reader(csv_file) | |
# Find the index of the full_name column | |
header_row = next(reader) | |
full_name_index = header_row.index('full_name') | |
# Create a new list to store the modified rows | |
modified_rows = [] | |
modified_rows.append(header_row + ['first_name', 'last_name']) | |
# Iterate over the rows in the file | |
for row in reader: | |
# Split the full_name into first_name and last_name | |
full_name = row[full_name_index] | |
name_parts = full_name.split(' ', 1) | |
if len(name_parts) == 1: | |
first_name = name_parts[0] | |
last_name = '' | |
else: | |
first_name, last_name = name_parts | |
# Add the modified row to the list | |
modified_rows.append(row + [first_name, last_name]) | |
# Open the file in write mode | |
with open(filename, 'w') as csv_file: | |
# Write the modified rows to the file | |
writer = csv.writer(csv_file) | |
writer.writerows(modified_rows) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment