2

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)
6
  • 1
    Did you come from a different programming language? because in python we don't need to define the size of the array, we can just create the list and we use list Commented Sep 14, 2018 at 9:42
  • 1
    please also try to provide us the sample content of indexes.txt so we can check what seems to be the problem Commented Sep 14, 2018 at 9:44
  • 1
    It would also be good if you explain why you want to use array rather than list. Commented Sep 14, 2018 at 9:49
  • If you want to do this with binary data, I think the easy way to determine the array size is to compute it from the file size. There are funcfions in the os module that can get the file size efficiently. Commented Sep 14, 2018 at 9:58
  • I use an array to save memory, I am working on a large problem Commented Sep 14, 2018 at 10:40

1 Answer 1

5

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())
Sign up to request clarification or add additional context in comments.

3 Comments

I am using Python 2.7 When I used you code, it tells me I cannot use "br", when I replace it with "r", I get the following error: AttributeError: 'array.array' object has no attribute 'frombytes'
@user58925 I made a bit of a mess, now it should work.
works perfect, thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.