python 3.x + Django 读取csv文件报错:'utf-8' codec can't decode byte 0xba in position 0: invalid start byte

报错示例:


csv文件中包含中文;

通过request读取文件内容的时候报错,


view.py 代码如下:

from django.shortcuts import render,render_to_response

def new_csvread(request):
    list = []
    if request.method == 'POST':
        instance = request.FILES.get('files')
        print(instance.read().decode('utf8'))
return render_to_response('csvread.html', {})


html代码如下:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>table</h1>
    <form method="post" enctype="multipart/form-data" >
    <input type="file" name="files" />
    <input type="submit" value="ok"/>
    </form>
</body>
</html>


启动服务之后,上传文件到后台;


原因:编码问题:

修改 view.py 的代码如下:

print(instance.read().decode('gb2312'))


详细地关于编码的问题,参考下面链接的内容:




猜你喜欢

转载自blog.csdn.net/wjunsing/article/details/78219079