How to read Python array from file?

Viewed 8862

I would like to write and read Python array from a txt file. I know to how to write it, but reading the array requires me to provide an argument about the length of the array. I do not the length of the array in advance, is there a way to read the array without computing its length. My work in progress code below. If I provide 1 as the second argument in a.fromfile, it reads the first element of the array, I would like all elements to read (basically the array to be recreated).

from __future__ import division
from array import array

L = [1,2,3,4]
indexes = array('I', L)

with open('indexes.txt', 'w') as fileW:
    indexes.tofile(fileW)

a = array('I', [])
with open('indexes.txt', 'r') as fileR:
    a.fromfile(fileR,1)
1 Answers

I don't know why .fromfile asks you to specify a number of objects but .frombytes doesn't. You can just read the bytes from the file and append them to the array.

This works in python3:

with open('indexes.txt', 'rb') as fileR:
    a.frombytes(fileR.read())
print(a)

prints:

array('I', [1, 2, 3, 4])

In python2 there is no .frombytes but .fromstring since str is equivalent to python3 bytes:

with open('indexes.txt', 'rb') as fileR: 
    a.fromstring(fileR.read())
Related