konstantin konstantin - 1 year ago 114
Python Question

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')]

Answer Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download