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.
Songs text file - the two letter code is a genre field
Country 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.
with open("countrydata.txt", newline="") as 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.