Question about reading a big binary file and write it into severaltext (ascii) files
Fredrik Lundh
fredrik at pythonware.com
Mon Jan 24 15:51:31 EST 2005
Albert Tu wrote:
> I am learning and pretty new to Python and I hope your guys can give me
> a quick start.
>
> I have an about 1G-byte binary file from a flat panel x-ray detector; I
> know at the beggining there is a 128-byte header and the rest of the
> file is integers in 2-byte format.
>
> What I want to do is to save the binary data into several smaller files
> in integer format and each smaller file has the size of 2*1024*768
> bytes.
>
> I know I can do something like
>>>>f=open("xray.seq", 'rb')
>>>>header=f.read(128)
>>>>file1=f.read(2*1024*768)
>>>>file2=f.read(2*1024*768)
>>>>......
(using a loop might help)
>>>>f.close()
>
> Bur I don't them how to save files in integer format (converting from
> binary to ascii files) and how to do this in an elegant and snappy way.
I think you have to define "integer format" a bit better. A text file with
integer values, written out in decimal?
If so, take a look at the array module:
http://docs.python.org/lib/module-array.html
Here's an (untested) example; tweak as necessary:
linesize = 1024
data = array("h", filedata)
for i in range(0, len(data), linesize):
# convert to list of decimal integers
list = map(str, data[i:i+linesize])
print " ".join(list)
tools like PIL and NumPy may also come in handy, but I suspect they're
overkill in this case.
</F>
More information about the Python-list
mailing list