![](/img/trans.png)
[英]Python script to use data from Azure Storage Blob by stream, and update blob by stream without local file reading and uploading
[英]Reading joblib file from Azure Blob in python
我正在嘗試從 Azure blob 讀取joblib
文件(請參見下面的代碼)。 但是,我收到以下錯誤:
with open(filename, 'rb') as f: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9d in position 2: invalid start byte
代碼:
from azure.storage.blob import BlobClient
import sklearn.externals
import joblib
blob_client = BlobClient.from_connection_string('connection_string', 'myContainer', 'myBlob.joblib')
downloaded_blob = blob_client.download_blob()
model = joblib.load(downloaded_blob.readall())
pickle
有loads()
可以正常工作。 如何使用 joblib 實現相同的目標?
由於讀取包含特殊字符的文件而導致的問題
Python 嘗試將字節數組(它假定為 utf-8 編碼字符串的字節)轉換為 unicode 字符串 (str)。 這個過程當然是按照utf-8規則進行解碼。 當它嘗試這樣做時,它遇到了 utf-8 編碼字符串中不允許的字節序列(即位置 0 處的這個 0xff)。
使用此解決方案,它將刪除(忽略)字符並返回沒有它們的字符串。 僅當您需要剝離它們而不是轉換它們時才使用它
with open(path, encoding="utf8", errors='ignore') as value:
使用errors='ignore'
你只會丟失一些字符。 但是如果您不關心它們,因為它們似乎是源自連接到我的套接字服務器的客戶端的錯誤格式和編程的額外字符。 那么它是一個簡單的直接解決方案。
參考: https : //docs.python.org/3/howto/unicode.html#the-unicode-type
解決問題的另一種方法
改變編碼方式。 此外,您可以在此處找到其他編碼方法標准編碼
我使用 readinto 而不是 readall (獲取 stream 並避免編碼問題),然后使用臨時文件將路徑讀入
def read_blob_model(azure_storage_connectionstring, container_name, path):
blob_client = BlobClient.from_connection_string(azure_storage_connectionstring, container_name, path)
downloaded_blob = blob_client.download_blob()
temp_file = tempfile.mkstemp()
with open(temp_file[1], 'wb') as f:
downloaded_blob.readinto(f)
return temp_file[1]
temp_file = read_blob_model(azure_storage_connectionstring, container_name, roomtype_model)
model = joblib.load(temp_file)
Joblib 也可以從BytesIO
而不是文件中讀取:
import BytesIO
import joblib
model_binary = BytesIO()
blob_client.download_blob().readinto(model_binary)
model = joblib.load(model_binary)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.