evanhaus
evanhaus

Reputation: 737

Having trouble reading CSV files with rows of different column count

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)

Upvotes: 0

Views: 49

Answers (1)

user2390182
user2390182

Reputation: 73470

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

Upvotes: 1

Related Questions