0

Rather than appending to the end of a file, I am trying to append to the end of a certain line of a .csv file. I want to do this when the user enters an input that matches the first column of the .csv.

Here's an example:

file=open("class"+classno+".csv", "r+")
writer=csv.writer(file)
data=csv.reader(file)

for row in data:
    if input == row[0]:
        (APPEND variable TO ROW)

file.close()

Is there a way to do this? Would I have to redefine and then rewrite the file?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
gulliver
  • 73
  • 2
  • 9
  • 4
    not trivially. a file is linear and you can't insert stuff in the middle of it. you need to re-write it if you want to add stuff in the middle – njzk2 May 04 '15 at 20:00
  • based on that comment you should rephrase your question... that is, if you have any questions left – Karoly Horvath May 04 '15 at 20:03
  • possible duplicate of [Is it possible to modify lines in a file in-place?](http://stackoverflow.com/questions/5453267/is-it-possible-to-modify-lines-in-a-file-in-place) – Peter Wood May 04 '15 at 20:03

1 Answers1

0

You can read the whole file then change what you need to change and write it back to file (it's not really writing back when it's complete overwriting).

Maybe this example will help:

read_data = []

with open('test.csv', 'r') as f:
    for line in f:
        read_data.append(line)

with open('test.csv', 'w') as f:
    for line in read_data:
        key,value = line.split(',')
        new_line = line

        if key == 'b':
            value = value.strip() + 'added\n'
            new_line = ','.join([key,value])

        f.write(new_line)

My test.csv file at start:

key,value
a,1
b,2
c,3
d,4

And after I run that sample code:

key,value
a,1
b,2added
c,3
d,4

It's probably not the best solution with big files.

ThePavolC
  • 1,693
  • 1
  • 16
  • 26