您好,登錄后才能下訂單哦!
寫了一個讀取log文件的Python腳本:
# -*- coding:utf-8 -*-
import os
import numpy as np
file = 'D:\pythonfile\test.log'
for line in open("test.log","r"):
print(line)
但是在執行時報錯:
執行代碼報錯:
Traceback (most recent call last):
File "D:/pythonfile/my-test225.py", line 8, in <module>
for line in open("test.log","r"):
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 6946: illegal multibyte sequence
Process finished with exit code 1
報錯如圖:
這是因為日志編碼格式和讀取日志的解碼格式不一致導致的
方法一,讀取文件指定“encoding='UTF-8':
# -*- coding:utf-8 -*-
import os
import numpy as np
file = 'D:\pythonfile\test.log'
for line in open("test.log","r",encoding='UTF-8'):
print(line)
方法二,讀取文件指定rb(rb 以二進制讀模式打開):
# -*- coding:utf-8 -*-
import os
import numpy as np
file = 'D:\pythonfile\test.log'
# for line in open("test.log","rb"):
print(line)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。