Liam Emery Liam Emery - 2 months ago 7
Python Question

How do I turn a list in a .txt file into a list in a python file?

I have a .txt file which contains 'lists'

3
[2,4,6,7]
[9,11,10,12,13]


And when I do
num_list = open("file.txt").read().splitlines()

then print it, my result is

['3','[2,4,6,7]','[9,11,10,12,13]']


How can I change it to make my result

[3, [2,4,6,7], [9,11,10,12,13]]


EDIT:
I tried this, and it's close

for i in num_list:
for j in i:
j.split(" ")
list(j)
print(j)


but now the output is

['2', '135', '2467']

Answer

Could use literal_eval:

import ast
with open('file.txt') as f:
    lists = [ast.literal_eval(line) for line in f]
print(lists)

prints

[3, [2, 4, 6, 7], [9, 11, 10, 12, 13]]