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']):
file.seek(len(row)) #this part is the problem I suppose
table = csv.writer(file)
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:
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: writer.writerow(row) if row == ['tbl']: writer.writerow() # empty line shutil.move('db.csv.temp', 'db.csv')