Tom Smith
Tom Smith

Reputation: 23

Reading a list of lists into Python

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

Upvotes: 0

Views: 711

Answers (1)

Mauro Baraldi
Mauro Baraldi

Reputation: 6560

>>> import ast
>>> with open('/path/to/data2.txt', 'r') as classes:
        lines = [ast.literal_eval(line.strip()) for line in classes]

>>> print lines
[['Tom', 7, 2, 1], ['Jo', 8, 0, 0], ['Adelphe', 9, 0, 0]]

Upvotes: 1

Related Questions