Re: write binary with struct.pack_into

Discussion in 'Python' started by Chris Angelico, Oct 6, 2012.

  1. On Sat, Oct 6, 2012 at 1:27 PM, palmeira <> wrote:
    > 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


    You have a beautiful parallel here, but I think that's where your
    problem is. In the READ section, you have fa.read() which will read
    the whole file, and then you slice the resulting string. That's pretty
    inefficient for large files, but it'll work.

    But when you write, that completely does not work. (Even assuming
    you've opened read/write, per Dennis's comment.)
    >>> fb.write()

    Traceback (most recent call last):
    File "<pyshell#37>", line 1, in <module>
    fb.write()
    TypeError: write() takes exactly 1 argument (0 given)

    It needs an argument of what to write out, it doesn't return a
    writable buffer suitable for pack_into.

    I recommend you completely rewrite your file handling to use actual
    seeks and file writes. Also, you'll want (I think) to use binary mode
    on your files; character encodings don't mean much when you're working
    with arrays of numbers.

    Finally, when you post issues, "ERROR in this WRITE" isn't very
    helpful. Please please post the full traceback (like in my trivial
    example above), as problems will be much more visible.

    Hope that's of some value!

    ChrisA
    Chris Angelico, 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. Peter Otten

    Re: write binary with struct.pack_into

    Peter Otten, Oct 6, 2012, in forum: Python
    Replies:
    0
    Views:
    167
    Peter Otten
    Oct 6, 2012
Loading...

Share This Page