clbx
clbx

Reputation: 184

Putting csv into list, accessing empty spaces in the last column gives a Index Out of Range

The list is a 2D list from a CSV imported using the following:

filedata = open('file.csv', 'r')
datareader = csv.reader(filedata, delimiter=',')
data = []
for row in datareader:
    data.append(row)

Here is an example of the spreadsheet

 |  0      1           2       
 |-------|--------|--------------|
0|   4   |   5    | home/user/a  |
1|   3   |   6    | home/user/b  |
2|       |        | home/user/b  |
3|   7   |   34   |              |

and in CSV format

4,5,home/user/a
3,6,home/user/b
,,home/user/b
7,34

The issue happens if I attempt to get a value in data that is blank in the CSV but only in the last row. So something like data[3][2] will give me an out of bounds error but if I call something like data[2][0] it works fine and just gives me blank back which is what i want.

Im thinking that it's not making the list at that row long enough, but I don't know how to make sure it is long enough

Im able to do a workaround to get all the information by checking the list length and if its less than the length of the complete lists, then it checks that value, but I feel that there is a much better way to do it then checking the lengths.

Upvotes: 2

Views: 246

Answers (1)

clbx
clbx

Reputation: 184

I found a solution, though it may only work in my case, I'm only looking for home/user/a, home/user/b or /home/user/c. You can use data[-1] and check the rightmost element in the array and can check to see what it is using that.

Upvotes: 1

Related Questions