2014-06-25 254 views
1

我有一個巨大的(1.5 GB)tsv(製表符分隔值)文件,我正在使用python處理,該文件是基於行的,但它有一些格式不正確的行,我希望跳過,我的代碼如下:程序意外終止

fo = open(output, 'w')  
with open(filename) as f: 
    i = 0 
    for line in f: 
     print i 
     try: #to account for the ill-formatted lines 
      user_hash, artist_hash, artist, playcount = line.split('\t') 
      fo.write('{0}\t{1}\t{2}'.format(hash_map[user_hash], artist, playcount)) 
      i = i+1 
     except: 
      print "error in user_hash : " + user_hash 
      continue 

現在的問題是程序儘快終止執行,能抓住的第一個例外,它只是打印「錯誤user_hash」,那麼存在。它應該繼續,因爲我知道該文件有1700萬行+和只達到433919.

爲什麼會發生這種情況?

感謝您的閱讀。

+2

該文件可能發生了某些情況,您無法再對其進行寫入,但很難看到,因爲您只是捕獲所有異常並不顯示任何內容。這就是爲什麼你不應該使用除了:。刪除它,看看有什麼例外。 – Oin

+0

'fo'是如何定義的? –

+0

@Oin引發的異常是ValueError: user_hash,artist_hash,artist,playcount = line.split('\ t') ValueError:需要超過3個值才能解壓 – hshihab

回答

0

我想我發現是什麼導致了問題,我正在閱讀的文件有很多'^ Z'字符,我認爲是什麼導致程序終止。

那麼檢測包含這些字符的行並在處理文件時忽略這些行的最佳方法是什麼?