简体   繁体   中英

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.

You could use eval ( https://docs.python.org/3/library/functions.html#eva ) to evaluate the text your read into Python data.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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