Python Forum
How to add new rows to existing csv file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to add new rows to existing csv file (/thread-17359.html)



How to add new rows to existing csv file - Sri - Apr-08-2019

Hi,

I have test.csv file as show below

Category Value
Initial Target 30
new target 49
recovery time [hrs] 2

Now I want to add new rows stored in string format (remove: ****new data****)

webdata:

****new data****
Reset time [min],78
Warning value,23
Error range, -4


I use the following code but it did not update.
webdata='****new data****
Reset time [min],78
Warning value,23
Error range, -4 '
import csv
with open(r'test.csv', 'a') as f:
    writer = csv.writer(f)
    writer.writerow(webdata)



RE: How to add new rows to existing csv file - Larz60+ - Apr-08-2019

A much safer way to do this, is to open a file for input,
read data until the place where you want to insert a new row, writing each row to the new file,
then insert new row,
continue reading old file, writing all rows to new file.
After you inspect the results and find they are OK, you can replace the old file with the new one.
I strongly advise keeping a backup of the original file first.
example read/write loop:
with open('test.csv', 'r') as f_in, open('testNew.csv', 'w') as f_out:
    reader = csv.reader(f_in, delimiter=',') # modify for your file
    writer = csv.writer(f_out, delimiter=',') # modify for your file
    for row in reader:
        writer.writerow(row)
        if row == ... # add insert condition
            writer.writerow(webdata)
Of course above code won't run until you add condition information.