Skip to content Skip to sidebar Skip to footer

Python Edit Csv Headers

I have the following data from a csv file called temp. Item,Description,Base Price,Available 2000-000-000-300,AC - CF/M Series Green For Black Hood,299.99,3 2000-000-000-380,AC - C

Solution 1:

The headers are just another row of CSV data. Just write them as a new row to the output followed by the rest of the data from the input file.

import csv
import os

inputFileName = "temp.csv"
outputFileName = os.path.splitext(inputFileName)[0] + "_modified.csv"withopen(inputFileName, 'rb') as inFile, open(outputFileName, 'wb') as outfile:
    r = csv.reader(inFile)
    w = csv.writer(outfile)

    next(r, None)  # skip the first row from the reader, the old header# write new header
    w.writerow(['Item Number', 'Item Description', 'List Price', 'QTY Available'])

    # copy the restfor row in r:
        w.writerow(row)

For Python 3, use:

withopen(inputFileName, newline='') as inFile, open(outputFileName, 'w', newline='') as outfile:

and you may have to specify an encoding for your data.

Solution 2:

Another solution is to use the fileinput module to update the file in place:

import fileinput
for line in fileinput.input('temp', inplace=True):
    if fileinput.isfirstline():
        print'Item Number,Item Description,List Price,QTY Available'else:
        print line,

Solution 3:

You could use fileinput for this:

import fileinput
import sys
import os

inputFileName = "temp.csv"
outputFileName = os.path.splitext(inputFileName)[0] + "_modified.csv"withopen(outputFileName, "w") as outfile:
    for line in fileinput.input(
        [inputFileName],
        inplace=False):
        if fileinput.isfirstline():
            outfile.write('Item Number,Item Description,List Price,QTY Available\n')
        else:
            outfile.write(line)

Post a Comment for "Python Edit Csv Headers"