无法重新打开 Django 文件作为 rb



为什么重新打开django.core.files文件作为二进制文件不工作?

from django.core.files import File
f = open('/home/user/test.zip')
test_file = File(f)
test_file.open(mode="rb")
test_file.read()

这给了我错误'utf-8' codec can't decode byte 0x82 in position 14: invalid start byte,所以在'rb'中打开显然不起作用。我之所以需要这个是因为我想以二进制

的形式打开FileField

您需要open(…)[Python-doc]二进制模式下的底层文件处理程序,所以:

with open('/home/user/test.zip', mode='rb') as f:
test_file = File(f)
test_file.open(mode='rb')
test_file.read()

如果不以二进制模式打开它,底层阅读器将尝试将其作为文本读取,从而在非utf-8码位的字节上出错。

最新更新