Athena Athena - 1 year ago 73
Python Question

add a new line after a specific line of a csv file in python3

I am writing a python code in which a csv file is read and some information are written in. I should find one specific row and add a new line of data after it, at this stage. I have succeeded finding the row but I can not write the new line of data after it. Here is my attempt:

file = open('db.csv', 'r+')
table = csv.reader(file)
for row in table:
if(row == ['tbl']): #this part is the problem I suppose
table = csv.writer(file)
table.writerow(['1', '2'])

Answer Source

Using / file.tell is tricky because csv.reader could read ahead; cannot tell exact file position that match current row.

Also inserting is not trivial; you need to remember remaing parts.

I would do it following way:

  • creating another file for write
  • write according to your need
  • once done, replace the old file with new file

import csv
import shutil

with open('db.csv', 'r', newline='') as f, open('db.csv.temp', 'w', newline='') as fout:
    reader = csv.reader(f)
    writer = csv.writer(fout)
    for row in reader:
        if row == ['tbl']:
            writer.writerow([])  # empty line

shutil.move('db.csv.temp', 'db.csv')