python novice python novice - 5 months ago 8
Python Question

Writing on the topmost row of a CSV file

I have this sample.csv file:

a 1 apple
b 2 banana
c 3 cranberry
d 4 durian
e 5 eggplant


And have the following code:

samplefile = open(sample.csv,'rb')
rows = samplefile .readlines()
outputfile = open(output.csv,'wb')
wr = csv.writer(outputfile)
for row in rows:
wr.writerow(row)


What I wanted to to is write on the first row of outputfile at some point during the for loop, i.e. when outputfile may already have entries.

Answer

If you want to add to the end of the file(append to it):

with open("sample.csv", "a") as fp:
     fp.write("new text")

If you want to overwrite the file:

with open("sample.csv", "w") as fp:
     fp.write("new text")

If you want to remove a line from file:

import fileinput
import sys

for line_number, line in enumerate(fileinput.input('myFile', inplace=1)):
  if line_number == 0:  #first line
    continue
  else:
    sys.stdout.write(line)

If you want to add a new first line(before the existing one):

with open("sample.csv", "r+") as fp:
     existing=fp.read()
     fp.seek(0) #point to first line
     fp.write("new text"+existing) # add a line above the previously exiting first line