Re: write binary with struct.pack_into

Discussion in 'Python' started by Peter Otten, Oct 6, 2012.

  1. Peter Otten

    Peter Otten Guest

    palmeira wrote:

    > Dear pythonists,
    >
    > I'm having a problem with read/write binary in python.
    > I have a binary file that I need to read information, extract a array,
    > modify this array and put these values into file again in same binary
    > format.
    > I need to use unpack_from and pack_into because sometimes gonna need
    > read/write in the middle of file.


    Use pack/unpack and file.seek() instead.

    > Script:
    >
    > import struct
    > bloco='>%df' %(252) #Binary format
    >
    > # READ
    > fa=open('testIN.bin')
    > my_array=struct.unpack_from(bloco,fa.read()[0*4:251*4]) # my_aray = 252
    > elements array
    > ## This read is OK!
    >
    > #WRITE
    > fb=open('testOUT.bin')
    > test=struct.pack_into(bloco,fb.write()[0*4:251*4]) # ERROR in this WRITE


    However, I think you have picked the wrong API. So:

    # untested

    import sys
    import array

    offset = 0
    N = 252

    a = array.array("f")
    with open("testIN.bin", "rb") as f:
    f.seek(offset)
    a.read(f, N)
    if sys.byteorder == "little":
    a.byteswap()

    # process a

    if sys.byteorder == "little":
    a.byteswap()
    with open("testOUT.bin", "wb") as f:
    f.seek(offset)
    a.write(f)
    Peter Otten, Oct 6, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Tzury Bar Yochay
    Replies:
    4
    Views:
    566
    John Machin
    Sep 21, 2008
  2. Hans Müller
    Replies:
    1
    Views:
    548
    Emile van Sebille
    Mar 19, 2010
  3. palmeira

    write binary with struct.pack_into

    palmeira, Oct 6, 2012, in forum: Python
    Replies:
    3
    Views:
    306
    Alexander Blinne
    Oct 6, 2012
  4. Dennis Lee Bieber

    Re: write binary with struct.pack_into

    Dennis Lee Bieber, Oct 6, 2012, in forum: Python
    Replies:
    2
    Views:
    167
    Chris Angelico
    Oct 6, 2012
  5. Chris Angelico

    Re: write binary with struct.pack_into

    Chris Angelico, Oct 6, 2012, in forum: Python
    Replies:
    0
    Views:
    205
    Chris Angelico
    Oct 6, 2012
Loading...

Share This Page