Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a list stored in a text file [duplicate]

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?

like image 605
Mustard Tiger Avatar asked Mar 24 '16 21:03

Mustard Tiger


2 Answers

You can use ast.literal_eval():

import ast

with open('filename.txt', 'r') as f:
    mylist = ast.literal_eval(f.read())
like image 142
pp_ Avatar answered Nov 02 '22 01:11

pp_


  1. rename the file from i.e. foo.txt to foo.py
  2. add my_list = in front of that line
  3. in your code: import foo; l = foo.my_list

Simpler, no? ;-)

like image 14
DevLounge Avatar answered Nov 02 '22 03:11

DevLounge