我正在測驗在 .jpg 檔案末尾寫入資料。據我所知,所有 .jpg 檔案都以 FFD8 開頭,以 FFD9 結尾。利用這個事實,我成功地撰寫了“Hello World!”。在我的 .jpg 檔案的末尾,其函式如下所示:
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!")
事實上,我得到:

但是現在我該怎么做才能只洗掉我在檔案末尾添加的資料(這意味著“你好世界!”
我試過這個:
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]
但它沒有用,我收到這個錯誤:
TypeError:“_io.BufferedWriter”物件不可下標
我在網上搜索了很多時間來解決我的問題,但沒有找到。
謝謝
uj5u.com熱心網友回復:
您應該改用bytes.rindex,因為這些ffd9位元組可能在檔案中出現多次:
$ 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])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/488396.html
