Binary files: Difference between revisions
(New page: Simple example of parsing a binary file. <source lang="python"> #!/usr/bin/python import os, sys fpath = sys.argv[1] size = os.stat(fpath)[6] print size, (size / 1024.0) file = open(fp...) |
(imported to nmm trac) |
||
(4 intermediate revisions by one other user not shown) | |||
Line 1: | Line 1: | ||
Simple example of parsing a binary file. | == Opening, Reading == | ||
'''IMPORTED''' | |||
Simple example of parsing a binary file (reads 1024 bytes, aka 1MB at a time). | |||
<source lang="python"> | <source lang="python"> | ||
Line 23: | Line 27: | ||
print count, "megabytes" | print count, "megabytes" | ||
</source> | </source> | ||
== Parsing == | |||
The Python [http://docs.python.org/library/struct.html struct] module is very useful for turning the "raw data" returned from read into Python data types (strings, numbers). |
Latest revision as of 16:15, 22 September 2009
Opening, Reading
IMPORTED
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"
Parsing
The Python struct module is very useful for turning the "raw data" returned from read into Python data types (strings, numbers).