Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: write binary with struct.pack_into

Reply
Thread Tools

Re: write binary with struct.pack_into

 
 
Chris Angelico
Guest
Posts: n/a
 
      10-06-2012
On Sat, Oct 6, 2012 at 1:27 PM, palmeira <(E-Mail Removed)> 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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
x86 binary runs; x86_64 binary throws segfault Don C Programming 60 03-19-2010 05:58 AM
(8-bit binary to two digit bcd) or (8-bit binary to two digit seven segment) Fangs VHDL 3 10-26-2008 06:41 AM
writing binary file (ios::binary) Ron Eggler C++ 9 04-28-2008 08:20 AM
A 64-bit binary returning a value to a 32-bit binary? spammenotplui31@yahoo.ca C Programming 12 04-08-2007 07:02 AM
Re: ostreams, ios::binary, endian, mixed binary-ascii Marc Schellens C++ 8 07-15-2003 12:27 PM



Advertisments