Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a new row in an existing csv file without appending it in the last line?

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

like image 216
Anne Avatar asked Jan 26 '26 02:01

Anne


1 Answers

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

like image 97
OneCricketeer Avatar answered Jan 28 '26 15:01

OneCricketeer