I am trying to add a new row to my old csv file. Basically, it gets updated each time I run the Python script.
Right now I am storing the old csv rows values in a list and then deleting the csv file and creating it again with the new list value.
Wanted to know are there any better ways of doing this.
Are you opening the file with mode of 'a' instead of 'w'?
See Reading and Writing Files in the python docs
Opening a file with the
'a'
parameter allows you to append to the end of the file instead of simply overwriting the existing content. Try that.I prefer this solution using the
csv
module from the standard library and thewith
statement to avoid leaving the file open.The key point is using
'a'
for appending when you open the file.You may experience superfluous new lines in Windows. You can try to avoid them using
'ab'
instead of'a'
.Based in the answer of @G M and paying attention to the @John La Rooy's warning, I was able to append a new row opening the file in
'a'
mode.I didn't try with the regular writer (without the Dict), but I think that it'll be ok too.