2015-06-23 143 views
3

我遇到問題,將代碼編寫爲Python 2.7,代碼與Python 3.4兼容。我收到outfile.write(decompressedFile.read())行中的錯誤TypeError: can't concat bytes to str。所以我用outfile.write(decompressedFile.read().decode("utf-8", errors="ignore"))取代了這一行,但是這導致了錯誤同樣的錯誤。嘗試將Python 2.7代碼轉換爲Python代碼時出現TypeError 3.4代碼

import os 
import gzip 
try: 
    from StirngIO import StringIO 
except ImportError: 
    from io import StringIO 
import pandas as pd 
import urllib.request 
baseURL = "http://ec.europa.eu/eurostat/estat-navtree-portlet-prod/BulkDownloadListing?file=" 
filename = "data/irt_euryld_d.tsv.gz" 
outFilePath = filename.split('/')[1][:-3] 

response = urllib.request.urlopen(baseURL + filename) 
compressedFile = StringIO() 
compressedFile.write(response.read().decode("utf-8", errors="ignore")) 

compressedFile.seek(0) 

decompressedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb') 

with open(outFilePath, 'w') as outfile: 
    outfile.write(decompressedFile.read()) #Error 
+0

不寫入模式已成爲''wb''? – TigerhawkT3

回答

3

的問題是,GzipFile需要換一個面向字節的文件對象,但你傳遞一個StringIO,這是面向文本。使用​​來代替:

from io import BytesIO # Works even in 2.x 

# snip 

response = urllib.request.urlopen(baseURL + filename) 
compressedFile = BytesIO() # change this 
compressedFile.write(response.read()) # and this 

compressedFile.seek(0) 

decompressedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb') 

with open(outFilePath, 'w') as outfile: 
    outfile.write(decompressedFile.read().decode("utf-8", errors="ignore")) 
    # change this too 
+0

謝謝。但是我現在得到錯誤'TypeError:'str'不支持'compressedFile.write(response.read()。decode(「utf-8」,errors =「ignore」))行中的緩衝接口'' – user131983

+1

@ user131983:已修復,請參閱編輯。你可能可以只執行'compressedFile = BytesIO(response.read())'... – Kevin