簡體   English   中英

Python UnicodeDecodeError:'utf8'編解碼器無法解碼位置74的字節0x80:無效的起始字節

[英]Python UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 74: invalid start byte

我在hbase中有一些數據存儲為以\\ x00填充定界的字節和字符串組合。

所以我的hbase中的行看起來像:-

00:00:00:00:00:00\x00\x80\x00\x00\x00U\xEF\xA0\xB00\x002\x0040.0.2.1\x00

該行(鍵)對應的值為100。

行說明:-

00:00:00:00:00:00 - This is mac address and is a string 
\x80\x00\x00\x00U\xEF\xA0\xB00 - This is the time which is saved as bytes
2 - this is customer id number stored as string
40.0.2.1 - this is store ID stored as string

我已經使用star base模塊將python連接到它的stargate服務器。

這是我的代碼片段,用於連接starbase和hbase表,並嘗試獲取該行的值:

from starbase import Connection
import starbase

C = Connection(host='10.10.5.2', port='60010')
get_table =  C.table('dummy_table')
mac_address = "00:00:00:00:00:00"
time_start = "\x80\x00\x00\x00U\xEF\xA0\xB00"
cus_id = "2"
store_id = "40.0.2.1"

create_query = "%s\x00%s\x00%s\x00%s\x00" % (mac,time_start,cus_id,store_id)

fetch_result = get_table.fetch(create_query)
print fetch_result

預期輸出為:-

100

您不必擔心starbase連接及其方法。 如果所有內容都是字符串,它們就可以正常工作,但是由於時間已轉換為字節,這給了我錯誤:

UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 74: invalid start byte

以防萬一我打印時需要查看create_query的輸出:-

00:00:1E:00:C8:36▒U▒v▒130.0.2.6

我非常感謝您的幫助。 謝謝

我的猜測是您的數據庫不支持在這些字段中存儲字節。 也許您必須存儲字符串。

一種方法是將字節轉換為base64字符串,然后再將其存儲在數據庫中。 例如:

>>> from base64 import b64encode, b64decode
>>> b64encode("\x80\x00\x00\x00U\xEF\xA0\xB00")
'gAAAAFXvoLAw'
>>> b64decode(_)
'\x80\x00\x00\x00U\xef\xa0\xb00'

嘗試這個

time_start = "\\x80\\x00\\x00\\x00U\\xEF\\xA0\\xB00"

\\ x是十六進制值的轉義序列,

create_query = "%s\x00%s\x00%s\x00%s\x00" % (mac,time_start,cus_id,store_id)

正在將time_start轉換為字符串。 由於x80不是有效的utf-8,因此它引發了錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM