29 lines
1.1 KiB
Python
29 lines
1.1 KiB
Python
|
import csv
|
||
|
|
||
|
input_file = "../data/passengers.csv"
|
||
|
output_file = "../data/passengers2.csv"
|
||
|
|
||
|
with open(input_file, 'r') as csv_input:
|
||
|
with open(output_file, 'w', newline='') as csv_output:
|
||
|
reader = csv.reader(csv_input)
|
||
|
writer = csv.writer(csv_output)
|
||
|
|
||
|
# Iterate through each row in the CSV
|
||
|
for row in reader:
|
||
|
# If the row is not empty
|
||
|
if row:
|
||
|
# Split name into last name and rest of name
|
||
|
split_name = row[3].split(',', 1)
|
||
|
|
||
|
if len(split_name) == 2:
|
||
|
lastname, rest_of_name = split_name
|
||
|
# further split name into salutation and first name
|
||
|
split_rest_of_name = rest_of_name.split('.', 1)
|
||
|
|
||
|
if len(split_rest_of_name) == 2:
|
||
|
salutation, first_name = [name.strip() for name in split_rest_of_name]
|
||
|
else:
|
||
|
salutation, first_name = split_rest_of_name[0], ""
|
||
|
|
||
|
row[3:4] = [first_name, salutation, lastname]
|
||
|
writer.writerow(row)
|