Skip to content Skip to sidebar Skip to footer

How To Insert Character In Csv Cell In Python?

I'm new with python. Here is my csv file : data;data;name surname; data; data data;data;name surname; data; data data;data;name surname; data; data data;data;name surname; data; da

Solution 1:

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

Solution 2:

>>> name_surname_regex = re.compile('^([^;]*;[^;]*;)([^\s]*\s[^\s]*)(.*)$')
>>> match_obj = name_surname_regex.match(data[1])
>>> for list_d in data:
        match_obj = name_surname_regex.match(list_d)
        print match_obj.group(1) + match_obj.group(2).replace(' ', ';') + match_obj.group(3)

trust me, if the data does not follow what you have given, you are bound to get lot of errors with the code


Post a Comment for "How To Insert Character In Csv Cell In Python?"