简体   繁体   English

如何从文件中读取python中的数组列表并将其放入数组列表中?

[英]How can i read a list of arrays in python from a file and put it in a list of array?

I have a list of array stored in a text file like this我有一个存储在这样的文本文件中的数组列表
[array([21,25,20]),array([12,24,23]),array([41,23,22])]
and i would like to read this file and put it also in a list because I have a function that only accepts a list.我想阅读这个文件并将它也放在一个列表中,因为我有一个只接受一个列表的函数。
The idea here is that the data is stored in the file as a string.这里的想法是数据作为字符串存储在文件中。
When I tried to use list() it puts quotations and I can't read the data in the way I want.当我尝试使用 list() 时,它会加上引号,但我无法以我想要的方式读取数据。

You could use eval ( https://docs.python.org/3/library/functions.html#eva ) to evaluate the text your read into Python data.您可以使用eval ( https://docs.python.org/3/library/functions.html#eva ) 来评估您读入 Python 数据的文本。

Make sure you trust the data source!确保您信任数据源!

Other than that, the current data you show is not valid Python, as the type code is missing - see https://docs.python.org/3/library/array.html除此之外,您显示的当前数据不是有效的 Python,因为缺少类型代码 - 请参阅https://docs.python.org/3/library/array.html

If you know the type code, you have to read the text, parse the data, add the type code manually, and then evaluate it.如果您知道类型代码,则必须阅读文本、解析数据、手动添加类型代码,然后对其进行评估。

Update - concerning the validity of the above data更新 - 关于上述数据的有效性

❯ 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
>>> 

... valid would be eg ... ...有效将是例如...

>>> [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])]
>>> 

I found an answer using pickle, pickle is a built-in way to save and load objects to a file.我使用pickle找到了一个答案,pickle是一种将对象保存和加载到文件的内置方法。

This is to write to a file这是写入文件

import pickle
with open('dataset_faces.dat', 'wb') as f:
    pickle.dump(encodeTest, f)

To read from a file从文件中读取

import pickle
with open('dataset_faces.dat', 'rb') as f:
    all_face_encodings = pickle.load(f)

and this is explanation to the problem and where i found the answer link这是对问题的解释以及我在哪里找到答案链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM