天天看點

Python2.7.3讀取日志資訊時發生讀取不完整的問題 1、問題:File reading problem2、解決方法:

 1、問題:File reading problem

OS environment : windows 7 Python version:2.7.3

  今天在使用Python以文本方式讀取一份日志文檔時,發生了怪異的問題,26464行的日志文檔,程式始終隻能讀出1980行。嘗試io.open方式,加上參數encoding='utf-8'問題依舊。

# certification_result_log -- record the result of certification
certification_result_log = open(r'C:\Users\lenovo\Desktop\Mchip_certification_result.txt','r+')

# log_file -- information source
log_file = open(r'C:\Users\lenovo\Desktop\ATM_BEP_2013-12-24.log','r')
for line in log_file:
     certification_result_log.write(line)
           

在多次使用16進制方式仔細對寫入目标檔案和源檔案進行比較時發現,他們均是在0x1A處被截斷,這個時候才想起windows環境下,以文本方式(text mode)讀入資料時,0x1A == 26 == ctrl-Z == EOF. 程式在讀取到0x1A,認為已經讀到檔案末尾。

相關問題參考: 1) http://stackoverflow.com/questions/7382838/file-reading-problem/ 2) http://www.redicecn.com/html/Python/20120110/364.html

2、解決方法:

OS environment : windows 7 Python version:2.7.3

暫時我隻想到對源目标檔案以二進制方式打開,進而将0x1A這個控制字元的意義忽略掉。

log_file = open(r'C:\Users\lenovo\Desktop\ATM_BEP_2013-12-24.log','rb')