3

I want to add a new row to an existing .csv file in python.

I tried by the following by appending a line to the csv file in spyder IDE in windows.

def write_to_file():

file = open('E:/Python/Sample//Dataset.csv','a')   
file.write(",".join([str(newID),request.form['username'],request.form['age']]))

file.close()

I expect the new values in a new row. But it is appending the new values in the last row.

If i add name "Erick" and Age "60", the output looks like the below image.enter image description here

But I expect something like the below.

enter image description here

Anne
  • 371
  • 5
  • 20

2 Answers2

2

What you're doing is correct, but you're assuming that the file already ends with a new line character

You need to put file.write("\n") before and/or after you've written each line

OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
  • Careful that if your file already ends with a newline, then you shouldn't write another one. Otherwise, you would then have empty lines... In such cases, using CSV as a "database replacement" is not a good idea – OneCricketeer Jun 01 '19 at 06:47
1

A simpler version would be:

import csv

row =['Eric', '60']

with open('people.csv','a') as csvFile:   #a to append to existing csv file
    writer = csv.writer(csvFile)
    csvFile.write("\n")    #write your data to new line
    writer.writerow(row)
csvFile.close()

Output (assuming your csv Doesn't end on new line):

enter image description here

Please be warned (If your csv ends on a newline) the output will have additional space:

enter image description here

Ajinkya
  • 1,687
  • 2
  • 21
  • 48
  • I checked it. It's working fine and it's not adding additional space. – Anne Jun 01 '19 at 10:06
  • Notice how prior "Before" image has 3 lines, whereas the later "before" text has 4 lines. If your csv ends on newline it will add space – Ajinkya Jun 02 '19 at 01:31