daikini
daikini

Reputation: 1337

How to replace a particular comma in a CSV file using Python?

I have quite a big CSV file where lines have varying length:

215080,49,3,0.0,22,42,0.0
215082,49,3,0.0,22,43,59.999 
215083,49,3,0.0,22,45,0.0
215085,49,3,0.0,22,46,59.999
215086,49,3,0.0,22,48,0.0
215087,49,3,0.0,22,49,0.001
215088,49,3,0.0,22,49,59.999
215089,49,3,0.0,22,51,0.0
215090,49,3,0.0,22,52,0.001
215688,49,1,59.999,22,49,0.001
215689,49,1,59.999,22,49,59.999
215690,49,1,59.999,22,51,0.0
215691,49,1,59.999,22,52,0.001
216291,49,1,0.001,22,51,0.0
216292,49,1,0.001,22,52,0.001
216293,49,1,0.001,22,52,59.999

I would like to replace, for example, only the fourth comma (,) in every line with a semicolon (;). How can I do this most efficiently?

Upvotes: 0

Views: 430

Answers (3)

S.Lott
S.Lott

Reputation: 391852

import csv
with open('source.csv','rb') as source:
    rdr= csv.reader( source )
    with open('revised.csv','wb') as target:
        wtr= csv.writer( target )
        for r in rdr:
            wtr.writerow( (r[0], r[1], r[2], '{0};{1}'.format(r[3],r[4]), r[5], r[6]) )

Upvotes: 7

CB Bailey
CB Bailey

Reputation: 791909

You could do something like this on each line of input.

tmp = line.split(',', 4)
newline = '%s;%s' % (','.join(tmp[:4]), tmp[4])

Upvotes: 4

Cesar Canassa
Cesar Canassa

Reputation: 20173

Another approach

>>> a = '215080,49,3,0.0,22,42,0.0'
>>> b = a.split(',')
>>> ','.join(b[0:3] + [b[3] + ';'  + b[4]] + b[5:])
'215080,49,3,0.0;22,42,0.0'

Upvotes: 2

Related Questions