Binary files: Difference between revisions

From XPUB & Lens-Based wiki
No edit summary
No edit summary
Line 23: Line 23:
print count, "megabytes"
print count, "megabytes"
</source>
</source>
The Python [http://docs.python.org/library/struct.html struct] module is very useful for working with "raw data" in Python.

Revision as of 17:12, 8 April 2009

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

#!/usr/bin/python

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"

The Python struct module is very useful for working with "raw data" in Python.