在 Python 脚本中读取文件时如何处理非 ASCII 字符?

问题描述 投票:0回答:0

我正在编写一个 Python 脚本,该脚本需要从包含非 ASCII 字符的文件中读取数据。但是,当我运行脚本时,遇到以下错误消息:

“UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 10: invalid continuation byte”

我尝试使用以下代码将文件的编码指定为“utf-8”:

with open('data.txt', 'r', encoding='utf-8') as f:
    data = f.read()

不幸的是,这似乎仍然不起作用。

我预期的结果是能够从文件中读取数据而不会出现任何错误并正确处理非 ASCII 字符。

任何帮助和建议将不胜感激。

编辑:

data.txt
如下: (为了我的法语作业)

Bonjour, comment ça va ?
Je suis en train d'apprendre le français.
J'aime bien écouter de la musique française.
Ça fait longtemps que je n'ai pas mangé de croissants frais.
Il y a beaucoup de sites web en français.
Je vais prendre un café au lait s'il vous plaît.
Les macarons sont délicieux.
Je rêve de visiter la Tour Eiffel un jour.
Le vin français est très bon.
python unicode encoding file-io
© www.soinside.com 2019 - 2024. All rights reserved.