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)
user58925
  • 1,537
  • 5
  • 19
  • 28
  • 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` – Alleo Indong Sep 14 '18 at 09:42
  • 1
    please also try to provide us the sample content of `indexes.txt` so we can check what seems to be the problem – Alleo Indong Sep 14 '18 at 09:44
  • 1
    It would also be good if you explain why you want to use `array` rather than `list`. – PM 2Ring Sep 14 '18 at 09: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. – PM 2Ring Sep 14 '18 at 09:58
  • I use an array to save memory, I am working on a large problem – user58925 Sep 14 '18 at 10:40
  • This should have been closed because it makes no sense (it fundamentally confuses text and binary files), but it is not a duplicate (the expected file format does not match - it seems that a binary format was intended). – Karl Knechtel Aug 29 '23 at 19:34

1 Answers1

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())
Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56