首页 > 解决方案 > 读取存储为字节的文本文件

问题描述

我有一个文本文件,其中项目存储为字节,即b" Charg\xc3\xa9e de mission communication chez BRL Groupe". 如何将其读入 python 以便将其解码为 utf-8?

将其作为 'rb' 读入 python 将其转换为b'b" Charg\\xc3\\xa9e de mission communication chez BRL Groupe"'.

with open('bytes.txt', 'rb') as f:
    for line in f:
        print(line)

我想得到它,以便它打印解码的字符串,Chargée de mission communication chez BRL Groupe

标签: pythonencodingascii

解决方案


而不是解码,它将字符串转换为字节,你需要使用一些东西来评估字符串是什么。那就是 ast.literal_eval()

print(ast.literal_eval(line))

感谢您的投票!这是答案!


推荐阅读