python replace string method in read file as binary -


i opened image file in readbinary("rb") mode , stored data in variable. want replace values in binary values.. not working using usual replace method of string

f=open("a.jpg","rb") a=f.read()  ''' first line '\xff\xd8\xff\xe0\x00\x10jfif\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xe1\x00*exif\x00\x00ii*\x00\x08\x00\x00\x00\x0 '''  a=a.replace("ff","z") print  #but there's no change in 

can tell iam going wrong.. tried

a=a.replace(b'ff',b'z') 

but still output unchanged.

can tell iam supposed perform replacement?

i don't know version of python you're using (this kind of operations different between 2 , 3), try a = str(a) before executing replace method.

edit: python 2.7 reasonable way i've discovered want use built-in function repr. example:

>>> picture = open("some_picture.jpg", 'rb') >>> first_line = picture.readline() >>> first_line '\xff\xd8\xff\xe0\x00\x10jfif\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xe1\x00*exif\x00\x00ii*\x00\x08\x00\x00\x00\x01\x001\x01\x02\x00\x07\x00\x00\x00\x1a\x00\x00\x00\x00\x00\x00\x00google\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n' >>> repr(first_line) >>> "'\\xff\\xd8\\xff\\xe0\\x00\\x10jfif\\x00\\x01\\x01\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\xff\\xe1\\x00*exif\\x00\\x00ii*\\x00\\x08\\x00\\x00\\x00\\x01\\x001\\x01\\x02\\x00\\x07\\x00\\x00\\x00\\x1a\\x00\\x00\\x00\\x00\\x00\\x00\\x00google\\x00\\x00\\xff\\xdb\\x00\\x84\\x00\\x03\\x02\\x02\\x03\\x02\\x02\\x03\\x03\\x03\\x03\\x04\\x03\\x03\\x04\\x05\\x08\\x05\\x05\\x04\\x04\\x05\\n'" >>> repr(first_line).replace('ff', 'some_other_string') "'\\xsome_other_string\\xd8\\xsome_other_string\\xe0\\x00\\x10jfif\\x00\\x01\\x01\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\xsome_other_string\\xe1\\x00*exif\\x00\\x00ii*\\x00\\x08\\x00\\x00\\x00\\x01\\x001\\x01\\x02\\x00\\x07\\x00\\x00\\x00\\x1a\\x00\\x00\\x00\\x00\\x00\\x00\\x00google\\x00\\x00\\xsome_other_string\\xdb\\x00\\x84\\x00\\x03\\x02\\x02\\x03\\x02\\x02\\x03\\x03\\x03\\x03\\x04\\x03\\x03\\x04\\x05\\x08\\x05\\x05\\x04\\x04\\x05\\n'" 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -