Skip to main content
se añadieron 75 caracteres en el cuerpo
Origen Enlace
FJSevilla
  • 62.1k
  • 7
  • 43
  • 68

Si no quieres todas las columnas simplemente pásale un iterable con las que quieres al parámetro fielnames de csv.DictWritercsv.DictWriter y especifica el parámetro extrasaction como "ignore":

Si no quieres todas las columnas simplemente pásale un iterable con las que quieres al parámetro fielnames de csv.DictWriter y especifica el parámetro extrasaction como "ignore":

Si no quieres todas las columnas simplemente pásale un iterable con las que quieres al parámetro fielnames de csv.DictWriter y especifica el parámetro extrasaction como "ignore":

se añadieron 973 caracteres en el cuerpo
Origen Enlace
FJSevilla
  • 62.1k
  • 7
  • 43
  • 68

tuTu código puede quedar algo así:

import csv

input_file = 'report_2017_12_06_23_06_16UTC.csv'
output_file= "file.csv"

with open('report_2017_12_06_23_06_16UTC.csv'input_file) as csvfile, open("file.csv"output_file,  "w") as output:
    reader = csv.DictReader(csvfile)
    writer = csv.DictWriter(output, fieldnames=reader.fieldnames)
    writer.writeheader()
    for row in reader:
        row['fillRate'] = '{:.2f}'.format(float(row['fillRate']) * 100)
        row['domain'] = row['ddomain'] if row['domain'] == row['ddomain']\
                                           else row['ddomain'] + " (MD != MR)"
        writer.writerow(row)

Edición:

Si no quieres todas las columnas simplemente pásale un iterable con las que quieres al parámetro fielnames de csv.DictWriter y especifica el parámetro extrasaction como "ignore":

import csv

input_file = 'report_2017_12_06_23_06_16UTC.csv'
output_file= "file.csv"

with open(input_file) as csvfile, open(output_file,  "w") as output:
    reader = csv.DictReader(csvfile)
    cols = ("trafficChannel", "date", "domain", "country",
            "opportunities", "impressions", "fillRate")
    writer = csv.DictWriter(output, fieldnames=cols, extrasaction='ignore')

    writer.writeheader()
    for row in reader:
        row['fillRate'] = '{:.2f}'.format(float(row['fillRate']) * 100)
        row['domain'] = row['ddomain'] if row['domain'] == row['ddomain']\
                                           else row['ddomain'] + " (MD != MR)"
        writer.writerow(row)
trafficChannel,trafficChannelId,date,domain,ddomain,country,opportunities,impressions,fillRate
aaaa,,11/29/17,juegos.com,juegos.com,ES,994,8,0.80
aaaa,,11/29/17,vinted.cz,vinted.cz,CZ,203,1,0.49
aaaa,,11/29/17,collinsdictionary.com,collinsdictionary.com,BE,421,1,0.24
aaaa,,11/30/17,chatytvgratishd.me (MD != MR),chatytvgratishd.me,CO,490,1,0.20
aaaa,,11/30/17,androidpit.com.br,androidpit.com.br,BR,125,2,1.60
aaaa,,12/1/17,eredmenyek.com,eredmenyek.com,HU,230,1,0.43

tu código puede quedar algo así:

import csv


with open('report_2017_12_06_23_06_16UTC.csv') as csvfile, open("file.csv", "w") as output:
    reader = csv.DictReader(csvfile)
    writer = csv.DictWriter(output, fieldnames=reader.fieldnames)
    writer.writeheader()
    for row in reader:
        row['fillRate'] = '{:.2f}'.format(float(row['fillRate']) * 100)
        row['domain'] = row['ddomain'] if row['domain'] == row['ddomain'] else row['ddomain'] + " (MD != MR)"
        writer.writerow(row)
trafficChannel,trafficChannelId,date,domain,ddomain,country,opportunities,impressions,fillRate
aaaa,,11/29/17,juegos.com,juegos.com,ES,994,8,0.80
aaaa,,11/29/17,vinted.cz,vinted.cz,CZ,203,1,0.49
aaaa,,11/29/17,collinsdictionary.com,collinsdictionary.com,BE,421,1,0.24
aaaa,,11/30/17,chatytvgratishd.me (MD != MR),chatytvgratishd.me,CO,490,1,0.20
aaaa,,11/30/17,androidpit.com.br,androidpit.com.br,BR,125,2,1.60
aaaa,,12/1/17,eredmenyek.com,eredmenyek.com,HU,230,1,0.43

Tu código puede quedar algo así:

import csv

input_file = 'report_2017_12_06_23_06_16UTC.csv'
output_file= "file.csv"

with open(input_file) as csvfile, open(output_file,  "w") as output:
    reader = csv.DictReader(csvfile)
    writer = csv.DictWriter(output, fieldnames=reader.fieldnames)
    writer.writeheader()
    for row in reader:
        row['fillRate'] = '{:.2f}'.format(float(row['fillRate']) * 100)
        row['domain'] = row['ddomain'] if row['domain'] == row['ddomain']\
                                           else row['ddomain'] + " (MD != MR)"
        writer.writerow(row)

Edición:

Si no quieres todas las columnas simplemente pásale un iterable con las que quieres al parámetro fielnames de csv.DictWriter y especifica el parámetro extrasaction como "ignore":

import csv

input_file = 'report_2017_12_06_23_06_16UTC.csv'
output_file= "file.csv"

with open(input_file) as csvfile, open(output_file,  "w") as output:
    reader = csv.DictReader(csvfile)
    cols = ("trafficChannel", "date", "domain", "country",
            "opportunities", "impressions", "fillRate")
    writer = csv.DictWriter(output, fieldnames=cols, extrasaction='ignore')

    writer.writeheader()
    for row in reader:
        row['fillRate'] = '{:.2f}'.format(float(row['fillRate']) * 100)
        row['domain'] = row['ddomain'] if row['domain'] == row['ddomain']\
                                           else row['ddomain'] + " (MD != MR)"
        writer.writerow(row)
trafficChannel,date,domain,country,opportunities,impressions,fillRate
aaaa,11/29/17,juegos.com,ES,994,8,0.80
aaaa,11/29/17,vinted.cz,CZ,203,1,0.49
aaaa,11/29/17,collinsdictionary.com,BE,421,1,0.24
aaaa,11/30/17,chatytvgratishd.me (MD != MR),CO,490,1,0.20
aaaa,11/30/17,androidpit.com.br,BR,125,2,1.60
aaaa,12/1/17,eredmenyek.com,HU,230,1,0.43
Origen Enlace
FJSevilla
  • 62.1k
  • 7
  • 43
  • 68

El primer problema es que al hacer your_list = list(a) en cada fila del csv, al final a solo contiene la última fila. Para que tu aproximación fuera correcta deberias añadir a la lista (list.append) cada fila modificada dentro del for y al final iterar sobre ella escribiendo cada sublista como una fila.

No obstante, en vez de crear una lista que es poco eficiente (terminas con todo el csv en memoria y es lenta de construir), deberías usar csv.DictWriter para ir escribiendo directamente cada fila según vas iterando sobre el archivo original.

tu código puede quedar algo así:

import csv


with open('report_2017_12_06_23_06_16UTC.csv') as csvfile, open("file.csv", "w") as output:
    reader = csv.DictReader(csvfile)
    writer = csv.DictWriter(output, fieldnames=reader.fieldnames)
    writer.writeheader()
    for row in reader:
        row['fillRate'] = '{:.2f}'.format(float(row['fillRate']) * 100)
        row['domain'] = row['ddomain'] if row['domain'] == row['ddomain'] else row['ddomain'] + " (MD != MR)"
        writer.writerow(row)

Que para el csv de ejemplo que muestras:

trafficChannel,trafficChannelId,date,domain,ddomain,country,opportunities,impressions,fillRate
aaaa,,11/29/17,juegos.com,juegos.com,ES,994,8,0.00804829
aaaa,,11/29/17,vinted.cz,vinted.cz,CZ,203,1,0.004926108
aaaa,,11/29/17,collinsdictionary.com,collinsdictionary.com,BE,421,1,0.002375297
aaaa,,11/30/17,urldelivery.com,chatytvgratishd.me,CO,490,1,0.002040816
aaaa,,11/30/17,androidpit.com.br,androidpit.com.br,BR,125,2,0.016
aaaa,,12/1/17,eredmenyek.com,eredmenyek.com,HU,230,1,0.004347826

Obtenemos:

trafficChannel,trafficChannelId,date,domain,ddomain,country,opportunities,impressions,fillRate
aaaa,,11/29/17,juegos.com,juegos.com,ES,994,8,0.80
aaaa,,11/29/17,vinted.cz,vinted.cz,CZ,203,1,0.49
aaaa,,11/29/17,collinsdictionary.com,collinsdictionary.com,BE,421,1,0.24
aaaa,,11/30/17,chatytvgratishd.me (MD != MR),chatytvgratishd.me,CO,490,1,0.20
aaaa,,11/30/17,androidpit.com.br,androidpit.com.br,BR,125,2,1.60
aaaa,,12/1/17,eredmenyek.com,eredmenyek.com,HU,230,1,0.43