2016-03-10 43 views
0

當我在文件中循環行時,得到了UnicodeDecodeError。UnicodeDecodeError用for循環解析文件python3

with open(somefile,'r') as f: 
    for line in f: 
     #do something 

當我使用python 3.4時會發生這種情況。 通常我有一些文件包含一些沒有UTF-8字符。我想逐行解析文件並找到問題apper所在的行,並在這種非utf-8 appeard的行中得到確切的索引。我已經準備好了它的代碼,但它的工作原理蟒蛇2.7.9,但在Python 3.4中,我得到UnicodeDecodeError for循環執行時。 任何想法???

+0

'對於ind,行中列舉(f,1):print(ind)'會給你行號 –

回答

1

您需要以二進制模式打開文件,並一次解碼一行。試試這個:

with open('badutf.txt', 'rb') as f: 
    for i, line in enumerate(f,1): 
     try: 
      line.decode('utf-8') 
     except UnicodeDecodeError as e: 
      print ('Line: {}, Offset: {}, {}'.format(i, e.start, e.reason)) 

下面是結果我在Python3得到:

Line: 16, Offset: 6, invalid start byte 

果然,第16行,第6位是壞的字節。