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:
Is it possible to achieve this with Python in a portable way?
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.
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.
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.
Try this:
fh = open("filename.ext", "r+b") fh.seek(offset) fh.write(bytes) fh.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With