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
#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


Messages In This Thread
How to add new rows to existing csv file - by Sri - Apr-08-2019, 02:34 PM
RE: How to add new rows to existing csv file - by Larz60+ - Apr-08-2019, 05:49 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Converting a json file to a dataframe with rows and columns eyavuz21 13 14,225 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  Reading Specific Rows In a CSV File finndude 3 1,878 Dec-13-2022, 03:19 PM
Last Post: finndude
  [Answered] Retrieve a set of rows from text file knob 4 2,649 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 2,154 Dec-08-2021, 04:42 AM
Last Post: Jdesi1983
  rows from sql query need to write to a file as columns sjcsvatt 6 3,633 Oct-09-2021, 12:45 AM
Last Post: snippsat
  Pandas DataFrame combine rows by column value, where Date Rows are NULL rhat398 0 2,723 May-04-2021, 10:51 PM
Last Post: rhat398
  Copy column from one existing excel file to another file mkujawsk 0 7,803 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 10,065 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
  write mariadb table rows query to each file? shams 1 2,531 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 4,084 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