On 2017-02-20 17:55, Ganesh Pal wrote:
Hello Python world,
I am on Linux and Python 2.7 , I need some help to figure out what is
going wrong in the below piece of code
I am trying to replace seven bytes in the hexdumfile at a given offset
Program 1 works fine
#!/usr/bin/python
from qa.utils.easy_popen import run
import pdb
def replace_hex(fname, offset, newdata):
#pdb.set_trace()
with open(fname, 'r+b') as f:
#Show current contents
f.seek(offset)
stringdata = f.read(len(newdata))
print 'Current data:'
print '%08X: %s\n' % (offset, stringdata.encode('hex'))
#Replace data at offset with newdata
f.seek(offset)
f.write(newdata)
There's no need to explicitly close the file because when you leave the
'with' statement, it'll close the file for you; that's why it's used!
f.close()
It's best to unindent the following lines so that they're outside the
'with' statement (and the file will have been closed).
#print the data
cmd = 'hexdump -C %s' % (fname)
print cmd
out, err, ret = run(cmd)
print "Hexdump file data for corrupting"
print out, err, ret
return fname
fname = '/tmp/2017-02-20_08-42-22/file1.raw'
offset = 0x1
newdata = '64000101057804'.decode('hex')
replace_hex(fname, offset, newdata)
-200-1# python file_2.py
Current data:
00000001: 6400010105789a
hexdump -C /tmp/2017-02-20_08-42-22/file1.raw
Hexdump file data for corrupting
00000000 06 64 00 01 01 05 78 04 73 1c ab 58 08 f9 8b 3b
|.d....x.s..X...;| ==> Replaced
00000010 1e 00 a1 00 01 00 00 00 64 00 01 01 05 78 02 00
|........d....x..|
[snip]
--
https://mail.python.org/mailman/listinfo/python-list