2015-04-01 103 views
8

之前,我從互聯網上下載一個壓縮文件:下載Python中的錯誤大文件:壓縮文件結束結束流標記達到

with lzma.open(urllib.request.urlopen(url)) as file: 
    for line in file: 
     ... 

已經下載完畢後並處理的AA很大一部分文件,我最終得到了錯誤:

File "/usr/lib/python3.4/lzma.py", line 225, in _fill_buffer raise EOFError("Compressed file ended before the " EOFError: Compressed file ended before the end-of-stream marker was reached

我想,這可能是由下降或服務器沒有響應一段時間的互聯網連接造成的。如果是這樣的話,有沒有辦法讓它繼續嘗試,直到連接重新建立,而不是拋出異常。 我不認爲這是該文件的問題,因爲我手動從同一網站手動下載了許多像這樣的文件並手動解壓。我也可以用Python下載和解壓縮一些較小的文件。我嘗試下載的文件的壓縮大小約爲20 GB。

+0

在得到錯誤之前需要多長時間才能下載?一些防火牆/代理似乎在固定的超時後(例如10分鐘)終止連接。如果它在相同的時間間隔後總是失敗,那可能是一個線索...... – DNA 2015-04-01 08:48:33

+0

[Python LZMA:壓縮數據在達到流結束標記之前結束]的可能重複(http://stackoverflow.com/questions/37400583/python-lzma-compressed-data-ended-end-of-stream-marker-was-reached) – kenorb 2016-05-23 22:51:50

+1

我在嘗試使用'urllib在線處理一個非常大的文件時遇到同樣的問題.request.urlopen()'和'gzip'。大約12個小時,我得到了類似的追蹤。 – bmende 2016-06-29 20:21:02

回答

2

urllib.urlopen docs:

One caveat: the read() method, if the size argument is omitted or negative, may not read until the end of the data stream; there is no good way to determine that the entire stream from a socket has been read in the general case.

也許在巨大的規模/連接錯誤/超時lzma.open人次以上的原因。

2

這可能是liblzma的錯誤。解決方法嘗試添加:

lzma._BUFFER_SIZE = 1023 

在致電lzma.open()之前。

0

假設您需要下載一個大文件,最好在使用python將內容寫入文件時使用「寫入和二進制」模式。

您也可以嘗試使用python requests模塊以上的urllib模塊:

請參見下面的工作代碼:

import requests 
url="http://www.google.com" 
with open("myoutputfile.ext","wb") as f: 
    f.write(requests.get(url).content) 

你能測試的代碼並回答回來,如果它不解決不了你的問題。

致以問候

2

您是否嘗試過使用請求庫?我相信它提供了一個通過urllib的抽象。

以下解決方案應該適合您,但它使用請求庫而不是urllib(但請求> urllib!)。讓我知道你是否願意繼續使用urllib。

import os 
import requests 
def download(url, chunk_s=1024, fname=None): 
    if not fname: 
     fname = url.split('/')[-1] 
    req = requests.get(url, stream=True) 
    with open(fname, 'wb') as fh: 
     for chunk in req.iter_content(chunk_size=chunk_s): 
      if chunk: 
       fh.write(chunk) 
    return os.path.join(os.getcwd(), fname)