Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: write binary with struct.pack_into (http://www.velocityreviews.com/forums/t953109-re-write-binary-with-struct-pack_into.html)

Peter Otten 10-06-2012 07:45 AM

Re: write binary with struct.pack_into
 
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)




All times are GMT. The time now is 07:02 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.