问题描述
我有一个文件,其内容采用python列表的形式,例如:
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']
有什么方法可以将python文件读回到列表对象中吗?而不是使用.read()
并将整个文件读取为字符串.
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.
对于那些可能感兴趣的人,我遇到了使用(import ast)的奇怪问题,如上述问题的解决方案所示.
for those who may be interested i ran into a strange issue using (import ast) as suggested as a solution for the above problem.
我在其中使用的程序具有从yahoo finance python模块获取历史股票数据的功能.此函数与ast.literal_eval()无关.
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().
无论如何,每天收市后的每个晚上,我都会从Yahoo Finance收集新一批的历史数据,而昨晚我遇到了一个错误:simplejson.scanner.jsondecodeerror期望值.
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.
这很奇怪,因为它可以收集某些公司的数据,却为其他公司抛出错误,并且有时可以为同一家公司工作,但是一分钟后它就无法工作.在尝试了各种方法以调试并解决问题后,我记得最近添加了import ast,并认为我应该尝试查看它是否可能有效果,在删除import ast之后,程序将恢复正常工作.
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.
有人知道为什么导入ast会引起问题吗? @Apero为什么最初警告您不要使用eval或ast.literal_eval?
does anybody know why import ast caused issues? @Apero why did you initially warn against using eval or ast.literal_eval?
推荐答案
您可以使用 ast.literal_eval()
:
You can use ast.literal_eval()
:
import ast
with open('filename.txt', 'r') as f:
mylist = ast.literal_eval(f.read())
这篇关于读取存储在文本文件中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!