2017-06-26 38 views
0

比方說,我有echo "hello world" > test.bson.gz產生假GZ文件test.bson.gz,我曾嘗試:假`.gz`提高IO錯誤,「不是一個壓縮文件」

try: 
    bson_file = gzip.open('test.bson.gz', mode='rb') 
except: 
    print("cannot open") 

沒有異常會被抓到這裏來。 (真是奇怪,因爲這不是一個有效的GZ ...)

然後我做的:

data = bson_file.read(4) 

我會得到:

File "/usr/lib/python2.7/gzip.py", line 190, in _read_gzip_header 
    raise IOError, 'Not a gzipped file' 
IOError: Not a gzipped file 

有什麼辦法,我可以決定(甚至發現錯誤)當我試圖打開它時,這個.gz是否有效,是否等到我想閱讀它?

謝謝!

回答

1

您可以使用gzip.peek(n)

ň壓縮字節沒有推進該文件的位置。

try: 
    bson_file = gzip.open('test.bson.gz', mode='rb') 
    bson_file.peek(1) 
except OSError: 
    print("cannot open") 

這樣,你將捕獲錯誤,而無需耗費文件內容。

提示:您應該避免無條件地捕捉所有錯誤。我添加了except OSError,因爲IOError在Python 3.3中合併爲OSError - 請參閱PEP3151

+0

等等......看來這段代碼對於有效的BSON不起作用。試試'bson_file.peek(1)'獲得一個有效的'.bson.gz',你會發現它仍然可以捕獲錯誤。 – tclo2

相關問題