[Tutor] How to read all integers from a binary file?

Peter Otten __peter__ at web.de
Fri Oct 9 20:49:40 CEST 2015


David Aldrich wrote:

> Hi
> 
> I have a binary file of 32-bit unsigned integers. I want to read all those
> integers into a list.
> 
> I have:
> 
>     ulData = []
>     with open(ulBinFileName, "rb") as inf:
>         ulData.append(struct.unpack('i', inf.read(4)))
> 
> This obviously reads only one integer from the file.  How would I modify
> this code to read all integers from the file please?

While the obvious approach would be a loop

data = [] # no misleading prefixes, please
while True:
    four_bytes = inf.read(4)
    if len(four_bytes) != 4:
        if four_bytes:
            raise ValueError("number of bytes not a multiple of 4")
        break
    data.append(struct.unpack("i", four_bytes))


there is also the array module:

data = array.array("i", inf.read())

You can convert the array to a list with

data = data.tolist()

if necessary.



More information about the Tutor mailing list