I have a file whose content is in the form of a python list such as the following:
['hello','how','are','you','doing','today','2016','10.004']
Is there any way to read the python file back into a list object? instead of using .read()
and having the whole file just read as a string.
EDIT: for those who may be interested i ran into a strange issue using (import ast) as suggested as a solution for the above problem.
the program i used it in has a function which fetches historical stock data from the yahoo finance python module. this function is in no way related or dependent on the function which used ast.literal_eval().
anyways every night after market close i collect new batches of historical data from yahoo finance and last night i ran into an error : simplejson.scanner.jsondecodeerror expecting value.
it was strange because it would collect data just fine for some companies but throw the error for others, and sometime work for the same company but a minute later it would not work. after trying all kinds of things to debug and solve the issue remembered that the import ast was recently added and thought i should try to see if it could have an effect, after removing the import ast the program went back to workin as it normally did.
does anybody know why import ast caused issues? @Apero why did you initially warn against using eval or ast.literal_eval?
You can use ast.literal_eval()
:
import ast
with open('filename.txt', 'r') as f:
mylist = ast.literal_eval(f.read())
my_list =
in front of that lineimport foo; l = foo.my_list
Simpler, no? ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With