Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Edit CSV headers

Tags:

python

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 - CF/M Series Green For White Hood,299.99,3

I need to change the headers to read

Item Number,Item Description,List Price,QTY Available

I have been searching similar questions on here and haven't a solution that I can understand since I am relatively new to python programming. So far I have:

import csv
import os

inputFileName = "temp.csv"
outputFileName = os.path.splitext(inputFileName)[0] + "_modified.csv"

with open(inputFileName) as inFile, open(outputFileName, "w") as outfile:
    r = csv.reader(inFile)
    w = csv.writer(outfile)

Which I know only reads the original file and then will write to _modified. How do I select the current headers and then change them so that they write to the new file?

like image 754
barkl3y Avatar asked Apr 30 '13 18:04

barkl3y


2 Answers

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"

with open(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 rest
    for row in r:
        w.writerow(row)

For Python 3, use:

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

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

like image 158
Martijn Pieters Avatar answered Oct 05 '22 22:10

Martijn Pieters


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,
like image 25
Hai Vu Avatar answered Oct 05 '22 23:10

Hai Vu