Create nested lists from file columns (Python)… here is a solution to the problem.
Create nested lists from file columns (Python)
I’m trying to create a nested list with lines from a .txt file, but it doesn’t get to the form I want.
.txt file contents:
[1,2,3]
[2,3,4]
[3,4,5]
Code:
nested_List = []
file = open("example_File.txt",'r')
for i in file:
element = i.rstrip("\n")
nested_List.append(element)
arch.close()
return (esta)
The result I got:
['[1,2,3]', '[2,3,4]', '[3,4,5]']
What I want:
[[1,2,3],[2,3,4],[3,4,5]]
Solution
You need to convert the string representing the list to the actual list. You can use ast.literal_eval
like:
from ast import literal_eval
nested_list = []
with open("file1", 'r') as f:
for i in f:
nested_list.append(literal_eval(i))
print(nested_list)
Or use list comprehension like:
with open("file1", 'r') as f:
nested_list = [literal_eval(line) for line in f]
print(nested_list)
Result:
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]