Python Forum

Full Version: How to read a text file into a list or an array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have 2 txt files as following:
1st - '[4,6,3,5]'
2nd - '[3,6],[6,2,7]'

I wonder if there is anyway to read it into a list or an array like:
1st - array [4,6,3,5]
2nd - array [[3,6],[6,2,7]]
One can use Python built-in module ast function ast.literal_eval() for safe evaluation of strings (note that it gives tuple of lists, not list of lists):

>>> import ast
>>> first = '[4,6,3,5]'
>>> ast.literal_eval(first)
[4, 6, 3, 5]
>>> type(_)
list
>>> second = '[3,6],[6,2,7]'
>>> ast.literal_eval(second)
([3, 6], [6, 2, 7])
>>> type(_)
tuple 
Thank a lot! It worked perfectly.