[英]TypeError when trying to convert Python 2.7 code to Python 3.4 code
我在將下面為Python 2.7
編寫的代碼轉換為Python 3.4
兼容的代碼時遇到了問題。 我得到錯誤TypeError: can't concat bytes to str
在行outfile.write(decompressedFile.read())
中將TypeError: can't concat bytes to str
。 所以我用outfile.write(decompressedFile.read().decode("utf-8", errors="ignore"))
替換了這行,但這導致了錯誤相同的錯誤。
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
問題是GzipFile
需要包裝一個面向字節的文件對象,但是你傳遞的是一個面向文本的StringIO
。 請改用io.BytesIO
:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.