最近做一个关于正则匹配的项目,用open()打开UTF-8格式的文件,读取每一行的内容;由于一些文件中存在非UTF-8标准的字符,脚本执行会报错。在debug过程中发现,实际上不论你写的是read(1)(读取一个字节的内容)还是readline()(读取一行的内容),python库函数会一次性读取一大块内容,一旦这块数据中有非法字节,整个调用就会出错。
例如以下代码读取每一行内容并打印,实际上含有非法字符的行以及前后若干行都不会被打印出来。
while True:
try:
line = file.readline()
print(line, end='')
except:
continue
if line == '':
break
测试读取example.txt文件包含1000行的以下内容,注意在第500行前面添加了一个非法字节0xa0:
This is Line No. 0
…
…
…
This is Line No. 488
This is Line No. 489
This is Line No. 490
This is Line No. 491
This is Line No. 492
This is Line No. 493
This is Line No. 494
This is Line No. 495
This is Line No. 496
This is Line No. 497
This is Line No. 498
This is Line No. 499
非法字符0xa0This is Line No. 500
This