Question about Reading from text file with Python's Array class

Tim Chase python.list at tim.thechases.com
Sun Dec 18 14:33:13 EST 2011


On 12/18/11 12:33, traveller3141 wrote:
> To test this, I made a small sample file (sillyNums.txt) as follows;
> 109
> 345
> 2
> 1234556
>
> f=open("sillyNums.txt","r")
> data = array.array('i')
> data.fromstring(f.read(data.itemsize* bufferSize))
> print data
>
> The output was nonsense:
> array('i', [171520049, 171258931])
>
> I assume this has something to do with my incorrectly specifying how the
> various bit/bytes line up. Does anyone know if there's a simple explanation
> of how I can do this correctly, or why I can't do it at all?

It reads the bytes directly as if using struct.unpack() as in

 >>> data = '109\n345\n2\n123456'
 >>> print ' '.join(hex(ord(c))[2:] for c in data)
31 30 39 a 33 34 35 a 32 a 31 32 33 34 35 36
 >>> 0x0a393031 # 4 bytes
171520049

It sounds like you want something like

   from itertools import islice
   a = array.array('i')
   a.fromlist(map(int, islice(f, bufferSize)))

which will read the first 2 lines of the file (using islice() on 
the file-object and slicing the first 2 items), and map the 
string representations into integers, then pass the resulting 
list of integer data to the array.array.fromlist() method.

-tkc






More information about the Python-list mailing list