954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

IndexError in reading a CSV into a multidimensional array

I am working on a project that requires a CSV file to be read into a multidimensional array. I loop through the array, and set multidimensionalarray[x][n] to the corresponding data in the CSV file, but I keep getting IndexError: list index out of range. I can't figure out why, and I've tried a number of different ways to fix it. Naturally, I took to the internet and found several forum posts that were almost, but not quite applicable to this. The code is as follows:

def load():
	x = 0
	if not os.access('Database.csv', os.F_OK):
		commands.getoutput('touch Database.csv')
	file = csv.reader(open('Database.csv', 'rb'))
	for row in file:
		retArr[x].append([])
		retArr[x] = row
		x = x + 1
	return retArr


Any help or pointers to where I might get the information would be greatly appreciated.

rhguh
Newbie Poster
2 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

I suggest

def touch(filename):
    os.close(os.open(filename, os.O_WRONLY | os.O_CREAT, int("666", 8)))
    os.utime(filename, None)

def load(filename = 'Database.csv'):
    if not os.access(filename, os.F_OK):
        touch(filename)
    with open(filename, 'rb') as ifh:
        return list(list(row) for row in csv.reader(ifh))

Also, for your safety, indent python code with 4 spaces, no tab characters, and avoid module commands which is deprecated.

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

That worked fantastically, thanks so much!

rhguh
Newbie Poster
2 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: