2

I have the following CSV file.

Item Number,Item Description,List Price,QTY Available
3079-000-006-000,Covert GTX Liner Size 6,99.99,8
3079-000-007-000,Covert GTX Liner Size 7,99.99,36
3079-000-008-000,Covert GTX Liner Size 8,99.99,181

I need to limit the QTY Available to 10. So If row[3] is greater than 10 I want the value 10 to show up in that role. So far I have:

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)

    r.next()  
    w.writerow(['Item Number', 'Item Description', 'List Price', 'QTY Available'])

    for row in r:
        if row[3] >= 10:
            row[3] = 10
        w.writerow(row)

This turns all the values in the QTY Available column to 10 however I only want to change the ones that exceed 10. How can I limit the values to 10?

1
  • Sorry that was a copy error I have edited it. Commented Apr 30, 2013 at 21:40

1 Answer 1

3

You are comparing strings and integers; turn row(10) into an integer first before comparing:

for row in r:
    if int(row[3]) >= 10:
        row[3] = 10
    w.writerow(row)

It doesn't matter that you set row[3] to an integer for output as the csv.writer() will turn it back to a string again for you.

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

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.