Update a CSV file?

You can effectively update any existing file “in-place” by first giving it a temporary file name and then writing a new file with its original name.

import csv
import os

filename="mytestfile.csv"
tempfilename = os.path.splitext(filename)[0] + '.bak'
try:
    os.remove(tempfilename)  # delete any existing temp file
except OSError:
    pass
os.rename(filename, tempfilename)

with open(filename, mode="wb") as outfile:
    csvwriter = csv.writer(outfile, delimiter="|")
    with open(tempfilename, mode="rb") as infile:
        csvreader = csv.reader(infile, delimiter="|")
        csvwriter.writerow(next(csvreader))  # copy header
        for row in csvreader:  # update column in each row
            row[1] = float(row) / 100  # update column in each row of data
            csvwriter.writerow(row)

os.remove(tempfilename)

Leave a Comment