报错: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)

在这里插入图片描述
我试了网上的各种方法:包括如下

  1. 在代码前加上两行,实操不行
#-*- 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)
  1. 用编码格式 “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’。亲测有效

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐