ReadingFromABinaryFile

From XPUB & Lens-Based wiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Reading from a binary file

Opening, Reading

Simple example of parsing a binary file (reads 1024 bytes, aka 1MB at a time).

import os, sys
fpath = sys.argv[1]

size = os.stat(fpath)[6]
print size, (size / 1024.0)

file = open(fpath, "rb")
count = 0
while 1:
	chunk = file.read(1024)
	if not chunk:
		break
	count += 1
	print ".",
print

file.close()
print count, "megabytes"


Parsing

The Python struct module is very useful for turning the "raw data" returned from read into Python data types (strings, numbers).