Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple edit to a binary file in python

Tags:

python

io

binary

THIS SHOULD BE EASY! But i've been unable to find the answer to this question.

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

There has to be a simple way to edit four measly bytes! right?

like image 924
CodingWithoutComments Avatar asked Jan 05 '11 00:01

CodingWithoutComments


People also ask

How do you edit a binary file in Python?

Step 1: Searching for the word in the binary file. Step 2: While searching in the file, the variable “pos” stores the position of file pointer record then traverse(continue) reading of the record. Step 3: If the word to be searched exists then place the write pointer (to ending of the previous record) i.e. at pos.

How do I edit a binary file?

To open the Binary Editor on an existing file, go to menu File > Open > File, select the file you want to edit, then select the drop arrow next to the Open button, and choose Open With > Binary Editor.

How do you write to a binary file in Python?

Write Bytes to File in Python Example 1: Open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.


1 Answers

with open(filename, 'r+b') as f:
  bytes = f.read(4)
  newbytes = 'demo'
  f.seek(0)
  f.write(newbytes)
like image 140
Emilio Silva Avatar answered Sep 22 '22 08:09

Emilio Silva