2

I want to use a function to add a row of information to an existing csv file.

friend_info will be a tuple including [name, address, phone, DOB]

I have this code

def add_friend(friend_info, friends_list):
    with open(friends_list, 'a') as fapp:
        writer = csv.writer(fapp)
        writer.writerow(friend_info)

for some reason this code is adding to the last line of the csv (I want it to start on a new line)

the
  • 21,007
  • 11
  • 68
  • 101
Jared
  • 63
  • 1
  • 6
  • 1
    Part of the solution is to change `writerows` to `writerow`. – Steven Rumbalski Apr 05 '13 at 04:57
  • thank you. that has fixed my cell problem. how do i get it to write on a new line? – Jared Apr 05 '13 at 05:10
  • have a look [HERE](http://stackoverflow.com/questions/7200606/python3-writing-csv-files). If you are using Python3 perhaps you are missing the newline parameter when opening the file. – D-rk Apr 05 '13 at 06:53
  • im using python 2.7. thanks for that though. im having alook. i just cant get it to start on a new line. – Jared Apr 05 '13 at 07:09
  • This question is answered here: http://stackoverflow.com/questions/40304504/how-do-i-add-a-new-row-of-data-to-a-csv-file-with-python/40309344#40309344 – Ross Nov 02 '16 at 19:37

1 Answers1

1

I don't think that the CSV writer object is smart enough to know that it's appending onto existing CSV data. You're just giving it a file object and telling it to put new CSV data into that file, so it just starts writing where it can. To start a new row, you will need to read the existing data in first, append your new row(s), then write it back out.

Justin S Barrett
  • 636
  • 4
  • 14