Skip to main content
 首页 » 编程设计

从文本文件读取时的 Python 编码问题

2025年05月04日16webabcd

我正在读取一个包含单个单词 B\xc3\xa9zier 的文本文件。

我希望将其转换为等效的解码 utf-8 格式,即 Bézier 并将其打印到控制台。

我的代码如下:

foo=open("test.txt")   
for line in foo.readlines():   
    for word in line.split():   
        print(word.decode('utf-8')) 
foo.close() 

输出是:

B\xc3\xa9zier 

但是如果我这样做:

>>> print('B\xc3\xa9zier'.decode('utf-8')) 

我得到了正确的输出:

Bézier 

我无法弄清楚为什么会这样?

请您参考如下方法:

好像你在文件中有一个原始的 utf8 转义字符串,使用 string_escape 来解码它

with open('test.txt') as f: 
    for line in f: 
        for word in line.split(): 
            print(word.decode('string_escape').decode('utf-8')) 
 
 
Bézier