9

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?

3 Answers 3

18

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.

Sign up to request clarification or add additional context in comments.

12 Comments

The usual way to call next in Python 3 is next(r) (one parameter). For those who are using Python 2, it would be r.next(). (I can deduce from OP's comment that he didn't have a problem with your next invocation, though. ;)
@barkl3y: Yeah, group all the arguments into a single list or tuple first. (Just put a pair of square brackets or a second set of parens around the arguments.)
@JohnY: next() takes a default. If r is empty, next(r) throws StopIteration, while next(r, None) returns the default None instead.
@JohnY: and next() works great in Python 2 as well. By using next() your code becomes compatible between Python 2 and 3. In Python 3 you could also call r.__next__() but using next() is more pythonic.
Ah, old habit. next() was introduced in Python 2.6, and one of the platforms I use Python on was stuck at 2.3.3 until only recently.
|
1

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,

Comments

0

You could use fileinput for this:

import fileinput
import sys
import os

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

with open(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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.