[Solved] How to insert character in csv cell in python?


You can tell Python’s split() to stop after a given number of matches by passing a maxsplit parameter. So in your case you just need to split after the first space as follows:

import csv

with open('input.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output, delimiter=";")

    for row in csv.reader(f_input, delimiter=";"):
        # Skip empty lines
        if len(row) > 3:
            try:
                name, surname = row[2].split(' ', 1)
            except ValueError as e:
                # No surname
                name, surname = row[2], ''

            row[2] = name
            row.insert(3, surname)
            csv_output.writerow(row)

So for an input with:

data;data;name surname1 surname2;data;data
data;data;name surname;data;data
data;data;name surname;data;data
data;data;name surname;data;data

You would get:

data;data;name;surname1 surname2;data;data
data;data;name;surname;data;data
data;data;name;surname;data;data
data;data;name;surname;data;data

6

solved How to insert character in csv cell in python?