I have made a list of lists to store score data for a given student. The list is called "class1" and each student has a name followed by 3 scores. I can sort this list fine and can write to a file which show the data in the correct format:
class1=[["Tom",7,2,1],["Jo",8,0,0],["Adelphe",9,0,0]]
When written look like this which I am happy with:
['Tom', 7, 2, 1]
['Jo', 8, 0, 0]
['Adelphe', 9, 0, 0]
The problem comes when I try to read the same list in. Each sublist is read as a string. I can't seem to change this.
Here is the code:
class1 = [line.strip() for line in open("data2.txt", 'r')]
This is what the list looks like when read, as you can see there are apostrophes around each sub list, meaning they are strings within the class1 list:
["['Tom', 7, 2, 1]", "['Jo', 8, 0, 0]", "['Adelphe', 9, 0, 0]"]
Can anyone help me, I've done a lot of searching, but can't find anyone with the same problem.
Thanks, Tom
split, notstrip.eval(string). If the string represents a list, it should become a python list object. I.e.class1 = [eval(line.strip()) for line in open("data2.txt", 'r')]picklemodule to write it and load it... will be more efficient that storing as text, then evaluating the input on reading again