我有一堆文本文件,其中有字节顺序标记(BOM(,而且它们还有CRLF(\r\n(结尾来标记行尾。例如,以下是八进制转储片段:
$ od -bc P21_T_3-28-2022.txt
0000000 357 273 277 163 164 141 147 145 040 061 015 012 120 154 141 171
357 273 277 s t a g e 1 r n P l a y
0000020 151 156 147 040 164 150 145 163 145 040 164 167 157 040 147 141
i n g t h e s e t w o g a
0000040 155 145 163 054 040 162 145 155 151 156 144 145 144 040 155 145
m e s , r e m i n d e d m e
0000060 040 157 146 040 164 151 155 145 163 040 164 150 141 164 040 111
o f t i m e s t h a t I
<snip>
我正在使用此代码读取文件:
lines = open(file, "r", encoding='utf-8').read().splitlines()
print(lines[0])
第一行是这样打印的,没有CRLF:
'ufeffstage 1'
如何在阅读时去掉BOM字符?
您可能需要将encoding
指定为utf-8-sig
:
lines = open(file, "r", encoding='utf-8-sig').read().splitlines()
print(lines[0])