0

I am having trouble reading through a file where the rows have different lengths. Specifically, I know that the file is 13 rows long and that rows 1 and 13 have 2 values in them where the rest (2-12) have 4. I want to get one value from row 1 and one value from row 13, and one value from each of rows 2-12 depending on whether or not their preceding value is equal to "credit" or "debit". Since the rows have different lengths I get 'index out of range' errors. Any help would be greatly appreciated. Thanks!

class Checkbook:
"""Checkbook class for list of check transactions"""

def __init__(self, filename):
    """initializer for Checkbook class"""

    self.name = filename
    self.debitList = []
    self.creditList = []
    self.startAmt = 0
    self.endAmt = 0
    self.shouldBeBal = 0

    with open(filename) as csvFile:
        readCSV = csv.reader(csvFile, delimiter = ',')

        #rowCount = sum(1 for row in readCSV) - 1
        #print(rowCount)

        next(csvFile)

        #in range(1, rowCount, 1):

        for row in readCSV:
            if (row[2] == " debit"):

                debitAmt = row[3]
                self.debitList.append(debitAmt)

            elif (row[2] == " credit"):
                creditAmt = row[3]
                self.creditList.append(creditAmt)
1
  • len(row) will give you the length of a row, so that you can use it in your logic. Commented Jun 3, 2016 at 2:22

1 Answer 1

1

Well, you have to either avoid the IndexError

for row in readCSV:
    if len(row) > 2:  # make sure the row is long enough
        if (row[2] == " debit"):  # now this can't fail
            # ...
        elif (row[2] == " credit"):
            # ...

or handle it:

for row in readCSV:
    try:
        if (row[2] == " debit"):
            # ...
        elif (row[2] == " credit"):
            # ...
    except IndexError:
        pass  # do nothing
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.