2

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.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
python novice
  • 379
  • 1
  • 4
  • 18
  • 1
    it's easier to finalize what you want to write to output.csv before writing to it – Fabricator Jun 15 '16 at 00:56
  • yup i got that , was just thinking if this way is possible. thank you :) – python novice Jun 15 '16 at 01:57
  • It cant be done : [Here is a link](http://stackoverflow.com/questions/125703/how-do-i-modify-a-text-file-in-python) to enumerate on this topic. – kaiser Jun 15 '16 at 05:27
  • 2
    Possible duplicate of [Inserting Line at Specified Position of a Text File](http://stackoverflow.com/questions/1325905/inserting-line-at-specified-position-of-a-text-file) – Bhargav Rao Jun 15 '16 at 07:59
  • @Bhargav Rao the link may provide other ways and could be used to further improve the process, let me chew on this and try to work out if it is the same as to what i wanted. Thank you. – python novice Jun 15 '16 at 23:27

1 Answers1

5

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
Community
  • 1
  • 1
Ani Menon
  • 27,209
  • 16
  • 105
  • 126