3

My txt file looks like this:

[[1,3,5],[1,4,4]]
[[1,4,7],[1,4,8],[2,4,5]]

And I was trying to convert it into a list, which include all the lists in the txt file. So the desired output for my example would be:

[[[1,3,5],[1,4,4]], [[1,4,7],[1,4,8],[2,4,5]]]

It seems like an easy task, except that I could only get this:

['[[1,3,5],[1,4,4]]', '[[1,4,7],[1,4,8],[2,4,5]]']

Is there an easy way to convert the string type into a list?


The code I used :

input_list = []
with open("./the_file.txt", 'r') as f:
    lines = f.read().split('\n')
    for each_line in lines:
        input_list.append(each_line)

f.close()
datadatadata
  • 323
  • 1
  • 3
  • 14

3 Answers3

5

You really want to evaluate each line in your file as actual python code. However, doing so can be problematic (e.g.: what happens if one line says import os; os.system('rm -rf /')).

So you don't want to use something like eval for this

Instead, you might consider using ast.literal_eval, which has a few safeguards against this sort of behavior:

with open("./the_file.txt", 'r') as f:
    answer = [ast.literal_eval(line.strip()) for line in f]
Community
  • 1
  • 1
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
2

This can be done in one line with ast.literal_eval and a list comprehension:

from ast import literal_eval

input_list = [literal_eval(line) for line in open("./the_file.txt", 'r') ]
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
0

If your lines in the text file are well formatted, you can use eval.

input_list.append(eval(each_line))
kampta
  • 4,748
  • 5
  • 31
  • 51