[英]Issues in Reading MemoryObject of file
MemoryObject
的函數。 它正在讀取大多數文件,但對於一個文件,它將引發UnicodeDecodeError
。 這是我的代碼
def read(file):
"""
:param file: File Memory Object (submitted from POST)
:return: File Iterable object
"""
file = StringIO(file.read().decode())
return csv.DictReader(file, delimiter=',')
完全錯誤如下: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte
open()
簡化文件,但是我已經簡化了MemoryObject,所以不能使用open()
您的file
已經以二進制模式打開: decode
是一種bytes
方法,而不是str
。
對於您的問題, encoding
和errors
的參數bytes.decode
作品一樣的open
。 您可以應用適當的編碼,或忽略錯誤:
def read(file, encoding: str = 'utf-8', errors: str = 'strict'):
"""
:param file: File Memory Object (submitted from POST)
:return: File Iterable object
"""
file = StringIO(file.read().decode(encoding=encoding, errors=errors))
return csv.DictReader(file, delimiter=',')
請注意,您必須知道編碼,或者通過忽略它們來抑制錯誤。 您可以嘗試使用不同的編碼來找到有效的編碼,但是最后您必須知道數據的含義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.