将csv转换为不同的csv

时间:2017-12-27 20:43:45

标签: python csv

我需要转换我的csv:

原件:

"DSP";"Fecha";"Moneda_a_pagar_a_medio";"Impresiones";"Importe_a_pagar_a_medio";"eCPM"
DSP;01/12/2017;USD;2.324;596,73;0,65

我在寻找什么:

DSP,Fecha,Moneda_a_pagar_a_medio,Impresiones,Importe_a_pagar_a_medio,eCPM
DSP,01/12/2017,USD,2324,596.73,0.65

代码:

import csv
with open('test.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')
    print spamreader

2 个答案:

答案 0 :(得分:2)

使用Pandas,将f更改为'test.csv'以从文件中读取:

import pandas as pd

data = '''\
"DSP";"Fecha";"Moneda_a_pagar_a_medio";"Impresiones";"Importe_a_pagar_a_medio";"eCPM"
DSP;01/12/2017;USD;2.324;596,73;0,65'''
f = pd.compat.StringIO(data)

df = pd.read_csv(f, sep=";", thousands='.', decimal=',')
df.to_csv('output.csv', index=False)

输出:

DSP,Fecha,Moneda_a_pagar_a_medio,Impresiones,Importe_a_pagar_a_medio,eCPM
DSP,01/12/2017,USD,2324,596.73,0.65

答案 1 :(得分:0)

import csv

with open('org.csv', 'r', newline='') as f:
    spamreader = csv.reader(f, delimiter=';', quotechar='|')
    data = list(spamreader)

with open('new.csv', 'w', newline='') as f:
    writer = csv.writer(f, delimiter=',', quotechar='|')
    writer.writerows(data)