faqts : Computers : Programming : Languages : Python : Common Problems : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 3 people (100%) answered Yes
Recently 3 of 3 people (100%) answered Yes

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))