如何使用Python替换CSV文件中的特定逗号?

时间:2011-12-21 23:03:20

标签: python csv

我有一个很大的CSV文件,其中行的长度各不相同:

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

例如,我想用分号(,)替换每行中的第四个逗号(;)。我怎样才能最有效地做到这一点?

3 个答案:

答案 0 :(得分:7)

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]) )

答案 1 :(得分:4)

你可以在每一行输入上做这样的事情。

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

答案 2 :(得分:2)

另一种方法

>>> 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'