python使用chardet来避免文件编码错误

在读取文件时,有时会遇到编码错误的讯息。

SyntaxError: (unicode error) ‘utf-8’ codec can’t decode byte 0xc4 in position 0:
invalid continuation byte

如果文件已知使用utf-8来编码,可以加上encoding参数:

with open('/path/to/file', 'r', encoding="utf-8") as f:
    print(f.read())

那我们也可以安装这个chardet套件来侦测未知文件的编码:

pip install chardet
chardet.detect("Today is tuesday.")

可以查看字典型态的回传:
{'confidence': 1.0, 'encoding': 'ascii'}

那也可以应用在flask上来读取上传的文件:

from flask import Flask,request
import chardet
import pandas as pd


app = Flask(__name__)

@app.route("/", methods=["POST"])
def hello_world():
    file = request.files.get('file')
    codingType = chardet.detect(file.read() )
    print(codingType)
    file.seek(0)
    fileContent_csv = pd.read_csv(file, index_col=None ,encoding= codingType['encoding'])
    fileContent_pd = pd.DataFrame(data=fileContent_csv)


    return "<p>Hello, World!</p>"


if __name__ == "__main__":
    app.run(debug=True,threaded=True)    


<<:  Day 28 | Unity游戏开发 - 介面设置及场景转换

>>:  学习Python纪录Day27 - Regular Expression正规表达式

Day 28 - Learned Index实作(2)

延续昨天的实作,首先我们先来修改一下昨天建置的 Learned Index 类别,还有一些参数需要储...

C# 入门之逻辑判断(上)

在讲逻辑判断之前,我们需要了解一下 C# 中的比较运算符,在前面的数据类型和运算符的介绍中,我们有介...

Day 27:开始撰写 Playbook

今天努力了一个下午,终於算是勉强搞出了一组能动的 playbook,这边就来记录一下过程以及就我所知...

Day 08:初步了解 Angular 应用程序及元件

Angular 应用程序的组成 一个完整的 Angular 应用程序会至少包含一个模组(module...

Day13. UX/UI 设计流程之三: UI Flow (并使用Axure RP 实作)

UI Flow 的全名是 User Interface Flow,望文生意,也就是使用者点某个按钮会...