Python Edit CSV headers
python
Solution
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.
Problem
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?