0

I'm trying to replace the first line of a csv input file with a header. The first line is blank, 0. See image below.

enter image description here

I want the blank and 0 to be "ID" and "sil_score" respectively. See below:

enter image description here

But I keep getting this:

enter image description here

import csv
r = csv.reader(open('C:/Users/Desktop/Geosill/attempt1.csv')) 
lines = list(r)

lines[1][0] = 'ID'
lines[2][0] = 'sil_score'


writer = csv.writer(open('C:/Users/Desktop/Geosill/attempt3.csv', 'w'))
writer.writerows(lines)
bkGeog
  • 39
  • 6

3 Answers3

0

If you're looking to edit the first two lines of the .csv you'll have to change how you access the lines list.

You'll need to use

lines[0][0]='ID'
lines[0][1]='sil_score'

instead.

The output seems odd though, could be something weird with the csv import. Try opening the files in a text editor, might be easier to see what's going on.

e_nicolai
  • 108
  • 5
0

This will do it. newline='' should be used to fix the blank line issue you are seeing as well.

import csv

with open('input.csv',newline='') as f:
    r = csv.reader(f)
    lines = list(r)

lines[0] = ['ID','sil_score']

with open('output.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerows(lines)
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
-1

You can do this without using csv.writer. Try this:

with open('C:/Users/Desktop/Geosill/attempt1.csv', "r") as infile:
    lines = infile.readlines().rstrip().split(",")
lines[0] = ["ID", "sil_score"]
with open('C:/Users/Desktop/Geosill/attempt1.csv', "w") as outfile:
    for line in lines:
        outfile.write(",".join(line))

Hope this helps!

Krishnan Shankar
  • 780
  • 9
  • 29