Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite some bytes in the middle of a file with Python?

Tags:

I'd like to be able to overwrite some bytes at a given offset in a file using Python.

My attempts have failed miserably and resulted in:

  • overwriting the bytes at the offset but also truncating the file just after (file mode = "w" or "w+")
  • appending the bytes at the end of the file (file mode = "a" or "a+")

Is it possible to achieve this with Python in a portable way?

like image 360
sebastien Avatar asked Feb 03 '09 21:02

sebastien


People also ask

How do you overwrite part of a file in Python?

Overwrite a File in Python Using the file.truncate() method. First, open the file in reading mode using the open() method, read the file data and seek to the start of the file using the file. seek() method, write the new data and truncate the old data using the file. truncate() method.

How do you overwrite a value in Python?

We can also use a while loop to replace values in the list. While loop does the same work as for loop. In the while loop first, we define a variable with value 0 and iterate over the list. If value matches to value that we want to replace then we replace it with the new value.

Does Python write overwrite?

Basics of Writing Files in Python Available are two modes, writing to a new file (and overwriting any existing data) and appending data at the end of a file that already exists.


1 Answers

Try this:

fh = open("filename.ext", "r+b") fh.seek(offset) fh.write(bytes) fh.close() 
like image 51
Ben Blank Avatar answered Oct 22 '22 04:10

Ben Blank