Modify a csv file in python

0

I have a file in .csv and I want to add a name to each column without modifying its contents.

How could I do it?

Thank you very much.

    
asked by user94589 20.07.2018 в 22:47
source

1 answer

0

First of all you should read the file, then use the writerow something like this: Supogamos in the file I have something like this:

Coca cola   | 1.25
Hamburguesa | 2.50
............|...

the code would be something like this:

import csv
with open('ejemplo.csv',newline='') as f:
    r = csv.reader(f)
    data = [line for line in r]
with open('ejemplo.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerow(['Producto','Precio'])
    w.writerows(data)

Result:

__________________
PRODUCTO    | PRECIO
__________________
Coca cola   | 1.25
Hamburguesa | 2.50
............|...
__________________

I hope you sriva and luck !!

    
answered by 20.07.2018 в 23:00