1

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']
oneman
  • 811
  • 1
  • 13
  • 31
  • 1
    thank you for pointing out that there is a similar question but can i please ask why you go out of your way to search for a duplicate? – oneman Sep 30 '16 at 04:53

1 Answers1

2

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]]
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
John Coleman
  • 51,337
  • 7
  • 54
  • 119