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.

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to