[英]python3 converting binary data to string and back
我正在使用python3以二進制模式打開圖像,然后在特定標記(\\ xff \\ xda)處拆分該數據
該標記之后的所有內容都存儲在一個變量中,我想用該變量將所有a替換為e
但是在將二進制數據轉換為字符串時遇到麻煩:
UnicodeDecodeError:'ascii'編解碼器無法解碼位置13的字節0xe6:序數不在范圍內(128)
with open(filein, "rb") as rd:
with open(fileout,'wb') as wr:
img = rd.read()
if img.find(b'\xff\xda'): ## ff da start of scan
splitimg = img.split(b'\xff\xda', 1)
wr.write(splitimg[0])
scanimg = splitimg[1]
scanglitch = ""
scanimg = scanimg.encode()
for letter in scanimg :
if letter not in 'a':
scanglitch += letter
else :
scanglitch += 'e'
print(scanimg)
wr.write(b'\xff\xda')
content = scanglitch.decode()
wr.write(content)
編碼()和解碼()將二進制數據轉換為字符串並返回的正確方法嗎? 謝謝
處理二進制數據時,您將嘗試盡可能地保持二進制模式,尤其是因為不能保證您選擇的字符串編碼仍然可以表示所有值。
請記住,即使bytes
對象具有方便的類似於字符串的b'xyz'
語法,它們也基本上是8位無符號整數的列表。
filein = "download.jpeg"
fileout = "glitch.jpg"
with open(filein, "rb") as rd:
img = rd.read()
# We can happily crash here if there's no FFDA;
# that means we're not able to process the file anyway
prelude, marker, scanimg = img.partition(b"\xff\xda")
scanglitch = []
for letter in scanimg: # scanimg is a list of integers, so we have to use `ord()`
if letter != ord("a"):
scanglitch.append(letter)
else:
scanglitch.append(ord("e"))
with open(fileout, "wb") as wr:
wr.write(prelude)
wr.write(marker)
wr.write(bytes(scanglitch))
(我知道替換邏輯可以寫為列表理解,但我認為這樣會更友好。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.