Python Forum
How to add new rows to existing csv file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to add new rows to existing csv file
#1
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)
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,403 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  Reading Specific Rows In a CSV File finndude 3 981 Dec-13-2022, 03:19 PM
Last Post: finndude
  [Answered] Retrieve a set of rows from text file knob 4 1,787 Dec-22-2021, 07:45 PM
Last Post: knob
  The code I have written removes the desired number of rows, but wrong rows Jdesi1983 0 1,629 Dec-08-2021, 04:42 AM
Last Post: Jdesi1983
  rows from sql query need to write to a file as columns sjcsvatt 6 2,383 Oct-09-2021, 12:45 AM
Last Post: snippsat
  Pandas DataFrame combine rows by column value, where Date Rows are NULL rhat398 0 2,111 May-04-2021, 10:51 PM
Last Post: rhat398
  Copy column from one existing excel file to another file mkujawsk 0 5,610 Apr-14-2021, 06:33 PM
Last Post: mkujawsk
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 7,101 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
  write mariadb table rows query to each file? shams 1 1,872 Feb-02-2021, 04:10 PM
Last Post: buran
  Fetch Oracle DB rows & print it in HTML file with table's col headers in table format tssr_2001 1 2,981 Sep-04-2020, 01:39 PM
Last Post: ibreeden

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020