konstantin
konstantin

Reputation: 893

Read lines from text as a list in Python

I am read data from text file. Every line of my data have the following structure

(110, 'Math', 1, 5)
(110, 'Sports', 1,  5)
(110, 'Geography', 4, 10)
(112, 'History', 1,  9)
....

and when I am reading the data from the file it is parsed as a string. So for all the lines I parse the data in a list of strings. However I want to create a list of lists with the 4 different elements (intengers and strings). How can I read the file elementwise and not parse it as string?

My code for read the file is the following:

data1 = [line.strip() for line in open("data.txt", 'r')]

Upvotes: 1

Views: 214

Answers (2)

MMF
MMF

Reputation: 5921

Do as follow :

data1 = [line.strip(')').strip('(').split() for line in open("data.txt", 'r')]

Upvotes: 1

bereal
bereal

Reputation: 34322

Assuming that the format is always as you described (i.e. corresponds to the Python tuple syntax), this is easily done with ast.literal_eval():

>>> ast.literal_eval("(110, 'Math', 1, 5)")
(110, 'Math', 1, 5)

So, the full code is:

import ast
with open('data.txt') as fp:
    data = [ast.literal_eval(line) for line in fp]

Upvotes: 6

Related Questions