Sofía Iranzo
Sofía Iranzo

Reputation: 11

Add several rows header in an existing csv file

I have a group of csv files, and I need to add to all of them a specific header compounded by 6 different rows:

header = ['Plantillas.mot', 'version=1', 'nRows='+str(len(data1)), 'nColumns=7', 'inDegrees=yes', 'endheader']

I am trying everything, my last try:

header = ['Plantillas.mot', 'version=1', 'nRows='+str(len(data1)), 'nColumns=7', 'inDegrees=yes', 'endheader']
import csv
ordered_filenames = header
with open('mycsv.csv') as csvfile, open(rute+'/loadsol/result1.mot',"w",newline='') as result:
    rdr = csv.DictReader(csvfile, fieldnames=ordered_filenames)
    wtr = csv.DictWriter(result, ordered_filenames)
    wtr.writeheader()
    for line in rdr:
        wtr.writerow(line)

But that gives me all the header in the same row, and I need the header to appear like this:

Plantillas.mot
version=1
nRows=821
nColumns=7
inDegrees=yes
endheader

Thank you very much for your help!

Upvotes: 1

Views: 41

Answers (1)

gosuto
gosuto

Reputation: 5741

You could add a newline character to each header name and write that string:

header = ['Plantillas.mot', 'version=1', 'nRows='+str(len(data1)), 'nColumns=7', 'inDegrees=yes', 'endheader']
header = '\n'.join(header)

Upvotes: 1

Related Questions