Entry
How can i cut part (offset from start,length in hex) of a binary file and write it to a new file?
Nov 16th, 2007 20:12
Kevin Grover, Wernher,
import sys
def fileslice(fo, start, length):
fo.seek(start)
return fo.read(length)
def writeashex(data, file=sys.stdout):
file.write(''.join(['%02x' % (ord(x)) for x in data]))
fo = open('binary.bin','rb')
writeashex(fileslice(fo, 5, 20))
# If you want to write it to a file, change the last line to:
fout = open('outputfile.txt','w')
writeashex(fileslice(fo, 5, 20), fout)
# If you really wanted the output as binary (not hex),
# change the last line to
fout = open('outputfile.bin','wb')
fout.write(fileslice(fo, 5, 20))