I am testing to write data at the end of a .jpg file. As i know all the .jpg files begin by FFD8 and end by FFD9. Using that fact i succeeded in writting "Hello World!" at the end of my .jpg file with a function that looks like this:
def writte_at_the_end_of_jpg_fct (img_path:str, msg:str):
with open(img_path, 'ab') as fimg:
fimg.write(b"Hello World!")
But now how can i do to remove only the data that i ve added at the end of the file (that means "Hllo World!"
I ve tried this:
def erase_data_in_img_fct(img_jpg_file_path: str) -> None:
with open(img_jpg_file_path, 'rb') as fimg:
content = fimg.read()
offset = content.index(bytes.fromhex('FFD9'))
end_i = fimg.seek(offset 2)
with open(img_jpg_file_path, 'ab') as fimg:
fimg = fimg[0:end_i]
But it didn't work, i get this error:
TypeError: '_io.BufferedWriter' object is not subscriptable
I have searched a lot of time on the web an answer to my problem and didn't found it.
Thank you
CodePudding user response:
You should use bytes.rindex instead because the ffd9
bytes may occur multiple times in the file:
$ diff -u old.py new.py
--- old.py 2022-06-08 08:07:33.381031019 0100
new.py 2022-06-08 08:07:45.581315987 0100
@@ -1,8 1,8 @@
def erase_data_in_img_fct(img_jpg_file_path: str) -> None:
with open(img_jpg_file_path, 'rb') as fimg:
content = fimg.read()
- offset = content.index(bytes.fromhex('FFD9'))
offset = content.rindex(bytes.fromhex('FFD9'))
end_i = fimg.seek(offset 2)
- with open(img_jpg_file_path, 'ab') as fimg:
- fimg = fimg[0:end_i]
with open(img_jpg_file_path, 'wb') as fimg:
fimg.write(content[:end_i])