Skip to content Skip to sidebar Skip to footer

Python Csv, How To Append Data At The End Of A Row Whilst Reading It Line By Line (row By Row)?

I am reading a CSV file called: candidates.csv line by line (row by row) like follows: import csv for line in open('candidates.csv'): csv_row = line.strip().split(',') chec

Solution 1:

Do backup your file before trying just in case.

You can write a new temporary file and move that into the place over the old file you read from.

from tempfile import NamedTemporaryFile
import shutil
import csv

filename = 'candidates.csv'
tempfile = NamedTemporaryFile('w', delete=False)

withopen(filename, 'r', newline='') as csvFile, tempfile:
    writer = csv.writer(tempfile)

    for line in csvFile:
        csv_row = line.strip().split(',')
        csv_row.append(check_update(csv_row[7])) # this will add the data to the end of the list.
        writer.writerow(csv_row)

shutil.move(tempfile.name, filename)

Post a Comment for "Python Csv, How To Append Data At The End Of A Row Whilst Reading It Line By Line (row By Row)?"