Martin Bouhier
Martin Bouhier

Reputation: 361

How to change the default CSV separator?

I´m trying to read a csv file separate with ;.

Code:

import csv
with open('Ingresos_e_eCPM_por_fecha_y_cliente.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, quotechar='|')
    for row in spamreader:
        print ', '.join(row)

I have this csv data:

21/12/2017;En;229.620;18.508;8,06%;14,56;0,79
22/12/2017;En;204.042;48.526;23,78%;43,98;0,91
23/12/2017;En;102.613;20.223;19,71%;17,86;0,88
24/12/2017;En;90.962;19.186;21,09%;14,26;0,74
25/12/2017;En;60.189;12.654;21,02%;11,58;0,92

The problem is when I try to read with my python code, It shows me these:

21/12/2017;En;229.620;18.508;8, 06%;14, 56;0, 79
22/12/2017;En;204.042;48.526;23, 78%;43, 98;0, 91
23/12/2017;En;102.613;20.223;19, 71%;17, 86;0, 88
24/12/2017;En;90.962;19.186;21, 09%;14, 26;0, 74
25/12/2017;En;60.189;12.654;21, 02%;11, 58;0, 92

I need the data in the same way as the csv!

Upvotes: 0

Views: 2115

Answers (2)

jojomojo
jojomojo

Reputation: 1342

You should adjust the comma-seperated-value (csv) file delimiter to a semicolon delimiter=';':

import csv 
with open('Ingresos_e_eCPM_por_fecha_y_cliente.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')
    for row in spamreader:
        print ', '.join(row)

An alternative would be to use one of the provided dialects (the usual culprit for csv sperated by semicolon is excel):

import csv 
with open('Ingresos_e_eCPM_por_fecha_y_cliente.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, dialect='excel', quotechar='|')
    for row in spamreader:
        print ', '.join(row)

Upvotes: 2

tread
tread

Reputation: 11088

If you read the documentation you will see that you can specify a Dialect.delimiter telling the csv module what character is used to seperate fields.

csv.reader(csvfile, dialect='excel', **fmtparams)

The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect.

In your case:

spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')

Upvotes: 2

Related Questions