Easy binary editing in python

IT SHOULD BE EASY! But I could not find the answer to this question.

Using python, I want to read a binary in memory, change the first four bytes of the file, and then write the file back.

There should be an easy way to edit four dead bytes! is not it?

+3
source share
6 answers

Why read the entire file to change four bytes at the beginning? Shouldn't this work?

with open("filename.txt", "r+b") as f:
     f.write(chr(10) + chr(20) + chr(30) + chr(40))

Even if you need to read these bytes from a file to calculate the new values, you can still:

with open("filename.txt", "r+b") as f:
    fourbytes = [ord(b) for b in f.read(4)]
    fourbytes[0] = fourbytes[1]  # whatever, manipulate your bytes here
    f.seek(0)
    f.write("".join(chr(b) for b in fourbytes))
+11
source
C:\junk>copy con qwerty.txt
qwertyuiop
^Z
        1 file(s) copied.

C:\junk>\python27\python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('qwerty.txt', 'r+b')
>>> f.write('asdf')
>>> f.close()
>>> open('qwerty.txt', 'rb').read()
'asdftyuiop\r\n'
>>>
+2
source
with open(filename, 'r+b') as f:
  bytes = f.read(4)
  newbytes = 'demo'
  f.seek(0)
  f.write(newbytes)
+2

, ,

Python 3:

def binaryedit(fn):
 f=open(fn,mode='rb')
 fc=f.read()
 f.close()
 return b'rawr'+fc[4:]

Python 2:

def binaryedit(fn):
 f=open(fn,mode='rb')
 fc=f.read()
 f.close()
 return 'rawr'+fc[4:]

, / , . , .

+1

this should help. http://www.johnny-lin.com/cdat_tips/tips_fileio/bin_array.html

import Numeric as N import array

num_lon = 144 num_lat = 73 tmpfile = "tmp.bin"

fileobj = open(tmpfile, mode='rb') binvalues = array.array('f') binvalues.read(fileobj, num_lon * num_lat)

data = N.array(binvalues, typecode=N.Float)

data = N.reshape(data, (num_lat, num_lon))

fileobj.close()
0
source

This is very similar to HW, so I will not give the exact code. but there is enough information

  • You do not need to read the entire file in memory to change the first 4 bytes
  • Open the file in 'r + b' mode
  • Use f.seek (0) to find the beginning
  • Write 4 bytes of data using f.write ('ABCD')
  • Close the file
0
source

Source: https://habr.com/ru/post/1783529/


All Articles