![](/img/trans.png)
[英]How do I read from a file and put it into a list as an integer? Python
[英]How can i read a list of arrays in python from a file and put it in a list of array?
我有一个存储在这样的文本文件中的数组列表[array([21,25,20]),array([12,24,23]),array([41,23,22])]
我想阅读这个文件并将它也放在一个列表中,因为我有一个只接受一个列表的函数。
这里的想法是数据作为字符串存储在文件中。
当我尝试使用 list() 时,它会加上引号,但我无法以我想要的方式读取数据。
您可以使用eval
( https://docs.python.org/3/library/functions.html#eva ) 来评估您读入 Python 数据的文本。
确保您信任数据源!
除此之外,您显示的当前数据不是有效的 Python,因为缺少类型代码 - 请参阅https://docs.python.org/3/library/array.html
如果您知道类型代码,则必须阅读文本、解析数据、手动添加类型代码,然后对其进行评估。
更新 - 关于上述数据的有效性
❯ python3
Python 3.6.9 (default, Jul 17 2020, 12:50:27)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from array import array
>>> [array([21,25,20]),array([12,24,23]),array([41,23,22])]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: array() argument 1 must be a unicode character, not list
>>>
...有效将是例如...
>>> [array("i",[21,25,20]),array("i",[12,24,23]),array("i",[41,23,22])]
[array('i', [21, 25, 20]), array('i', [12, 24, 23]), array('i', [41, 23, 22])]
>>>
我使用pickle找到了一个答案,pickle是一种将对象保存和加载到文件的内置方法。
这是写入文件
import pickle
with open('dataset_faces.dat', 'wb') as f:
pickle.dump(encodeTest, f)
从文件中读取
import pickle
with open('dataset_faces.dat', 'rb') as f:
all_face_encodings = pickle.load(f)
这是对问题的解释以及我在哪里找到答案链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.