That Blue Square Thing

AQA Computer Science GCSE

Programming projects - File Handling

Reading 2–Dimensional Arrays

Two–dimensional arrays are arrays of arrays. Or in Python terms, lists of list.

Take a look at the text files to see what I mean.

Text file iconSongs text file - the two letter code is a genre field

Text file iconCountry data - the number is the population in millions

Reading this sort of array in is trickier using the file.read methods that I've discussed already. It's possible, but gets complex.

Fortunately there's an easy solution. Even more fortunately, you no longer have to memorise it to use in controlled assessment...

Reading in a list of lists

So, the clever thing is that this uses a library called csv. Once you have this in place, it's a piece of cake to read in the list of lists.

import csv # import the library

with open("countrydata.txt", newline="") as inputfile:
countryList = list(csv.reader(inputfile))

print(countryList) # print the list to check

Simples. The csv library takes care of nearly all the hard work.

It is also possible to get the csv library to save a two–dimensional array to a text file in a similar way. You can read about that on the advanced file writing page.