[英]Storing a list from a textfile
I have a textfile that contains a list on the first line. 我有一个文本文件,其中包含第一行的列表。 How can I read the file and store the first line in a list?
如何读取文件并将第一行存储在列表中? I want to store the first line as a complete list not as a string.
我想将第一行存储为完整列表而不是字符串。
Example of the textfile: 文本文件示例:
[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
It looks like your data is valid json: 看起来你的数据是有效的json:
>>> import json
>>> json.loads('[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]')
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
To load it from a file: 要从文件加载它:
with open('my_file.txt') as f:
my_list = json.load(f)
Similarly, yaml.load
and ast.literal_eval
could also handle that data. 同样,
yaml.load
和ast.literal_eval
也可以处理该数据。
You can use the ast
module 您可以使用
ast
模块
import ast
s = '[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]'
s = ast.literal_eval(s)
print s, type(s)
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] <type 'list'>
You can use ast.literal_eval()
like below: 您可以使用
ast.literal_eval()
:
>>> import ast
>>>
>>> ast.literal_eval('[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]')
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
This is why you should use ast.literal_eval()
to evaluate your string: 这就是为什么你应该使用
ast.literal_eval()
来评估你的字符串:
ast.literal_eval(node_or_string)
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python literal or container display.
安全地评估表达式节点或包含Python文字或容器显示的字符串。 The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
提供的字符串或节点可能只包含以下Python文字结构:字符串,字节,数字,元组,列表,dicts,集合,布尔值和None。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.