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.

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.

That worked fantastically, thanks so much!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.