Reading binary file, convert raw bytes 
Author Message
 Reading binary file, convert raw bytes

tom asks:

Quote:
> I can open and read a binary file with the following code:

> filename = 'BIN/head.binS'

> f = open(filename, 'rb')
> f.seek(4)
> kstp = f.read(4)    # integer
> kper = f.read(4)    # integer
> pertim = f.read(4)  # float
> totim = f.read(4)   # float
> text = f.read(16)   # text

> Now, how do i convert the 'raw bytes' in the strings to the
> corresponding numbers?

import struct

recdef = 'llff16s'      # 2 longs, 2 floats, 16 chars as a string
reclen = struct..calcsize(recdef)
...
f.seek(4)
rawrec = f.read(reclen)
(kstp, kper, pertim, totim, text) = struct.unpack(recdef, rawrec)

- Gordon



Mon, 27 Nov 2000 03:00:00 GMT  
 Reading binary file, convert raw bytes

Quote:
> I can open and read a binary file with the following code:

> filename = 'BIN/head.binS'

> f = open(filename, 'rb')
> f.seek(4)
> kstp = f.read(4)    # integer
> kper = f.read(4)    # integer
> pertim = f.read(4)  # float
> totim = f.read(4)   # float
> text = f.read(16)   # text

> Now, how do i convert the 'raw bytes' in the strings to the corresponding
> numbers?

Ah -- this wasn't in the FAQ.  Now it is.  Here's the new entry:

4.79. How do I read (or write) binary data?

Use the struct module.  It's documented in the library reference.
It allows you to take a string read from a file containing binary
data (usually numbers) and convert it to python objects; and vice
versa.

For example, the following code reads two 4-byte integers in big-endian
format from a file:

  import struct

  f = open(filename, "rb")  # Open in binary mode for portability
  s = f.read(8)
  x, y = struct.unpack(">ll", s)

The '>' in the format string forces bin-endian data; each letter
'l' reads one "long integer" (4 bytes) from the string.

--Guido van Rossum (home page: http://www.python.org/~guido/)



Mon, 27 Nov 2000 03:00:00 GMT  
 
 [ 4 post ] 

 Relevant Pages 

1. Reading in a file as raw hex bytes?

2. read n bytes from a binary file

3. Reading a binary file / writing binary data to a file

4. Using DEC Fortran to read raw binary data?

5. converting 1 byte binary to display

6. Converting VMS binary files to PC binary

7. Reading binary files, unflatten binary string

8. Reading raw double from file

9. Converting big-endian byte to small-endian byte

10. Converting big-endian byte to small-endian byte

11. Binary File with partial Byte

12. Writing binary data to a file without carriage returns every 512 bytes

 

 
Powered by phpBB® Forum Software