Inline CSV File Editing with Python

No, you should not attempt to write to the file you are currently reading from. You can do it if you keep seeking back after reading a row but it is not advisable, especially if you are writing back more data than you read.

The canonical method is to write to a new, temporary file and move that into place over the old file you read from.

from tempfile import NamedTemporaryFile
import shutil
import csv

filename="tmpEmployeeDatabase.csv"
tempfile = NamedTemporaryFile('w+t', newline="", delete=False)

with open(filename, 'r', newline="") as csvFile, tempfile:
    reader = csv.reader(csvFile, delimiter=",", quotechar=""")
    writer = csv.writer(tempfile, delimiter=",", quotechar=""")

    for row in reader:
        row[1] = row[1].title()
        writer.writerow(row)

shutil.move(tempfile.name, filename)

I’ve made use of the tempfile and shutil libraries here to make the task easier.

Leave a Comment