admin管理员组文章数量:1612060
报错:UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0x89 in position 0: invalid start byte 解决办法
from fastapi import FastAPI,Response
import uvicorn
app=FastAPI()
@app.get("/{path}")
def index(path):
print(path)
with open(f"WebServer_html/{path}","r",encoding="UTF-8") as f:
content = f.read()
return Response(content=content)
uvicorn.run(app,host="192.168.82.163",port=9999)
运行后出错:
更改成gbk格式也不行
from fastapi import FastAPI,Response
import uvicorn
app=FastAPI()
@app.get("/{path}")
def index(path):
print(path)
with open(f"WebServer_html/{path}","r",encoding="GBK") as f:
content = f.read()
return Response(content=content)
uvicorn.run(app,host="192.168.82.163",port=9999)
我试了网上的各种方法:包括如下
- 在代码前加上两行,实操不行
#-*- coding : utf-8-*-
# coding:utf-8
from fastapi import FastAPI,Response
import uvicorn
app=FastAPI()
@app.get("/{path}")
def index(path):
print(path)
with open(f"WebServer_html/{path}","r",encoding="UTF-8") as f:
content = f.read()
return Response(content=content)
uvicorn.run(app,host="192.168.82.163",port=9999)
- 用编码格式 “unicode_escape”
运行确实不出错了,但是运行后中文变成乱码,不行
from fastapi import FastAPI,Response
import uvicorn
app=FastAPI()
@app.get("/{path}")
def index(path):
print(path)
with open(f"WebServer_html/{path}","r",encoding="unicode_escape") as f:
content = f.read()
return Response(content=content)
uvicorn.run(app,host="192.168.82.163",port=9999)
解决办法如下:
# with open(f"WebServer_html/{path}","r",encoding="UTF-8") as f:
with open(f"WebServer_html/{path}","r",encoding="UTF-8",errors='ignore') as f:
在encoding参数后面加上,errors参数并设置为’ignore’。亲测有效
本文标签: 报错UTFCodecPythonUnicodeDecodeError
版权声明:本文标题:Python——报错UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0x89 in position 0: invalid start byte 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1728604514a1165282.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论