python - 文件第一行中包含的 unicode header

标签 python python-3.x

我正在打印文件的第一行:

with open(path,"r",encoding='utf8') as f:
    for i, l in enumerate(f.readlines()):
        print(bytes(l.rstrip(), encoding='utf8'))

我希望输出 b'1' 但我得到的是:

b'\xef\xbb\xbf1'

这里有什么问题?

我在 Windows 上,我使用 Notepad++ 保存我的文件。

最佳答案

要正确解析 BOM,请使用 utf-8-sig :

with open(path,"r",encoding='utf-8-sig') as f:

关于python - 文件第一行中包含的 unicode header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11042173/

相关文章:

python - 检测 Ctrl+S ionic QTextedit?

Python Pip 安装 : not recognised as a batch file. ... 在命令提示符窗口中

python - python正则表达式不会忽略行尾的空格

python - 在pytorch的神经网络中将参数限制为-1、0或1

python - 无法在python中运行turtle类

python - 在字典中绘制嵌套列表 - python

python - 打印 pandas 列之间的增量差异

python - 使用 OpenCV python 捕获 rtsp 相机

python OOP,访问属性

python - 将 CMD 命令与可执行 python 脚本结合使用