使用urllib.request代替urllib2时的TypeError

时间:2015-06-22 21:30:35

标签: python

我正在尝试将之前为Python 2.7编写的代码转换为可在Python 3.4中运行的代码。代码如下,我必须将urllib2.urlopen()更改为urllib.request.urlopen()。但是,此更改导致行TypeError: string argument expected, got 'bytes'中出现错误compressedFile.write(response.read())

import os
import urllib2
import gzip
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO
import pandas as pd

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 = urllib2.urlopen(baseURL + filename) #Changed this to urllib.request.urlopen()
compressedFile = StringIO()
compressedFile.write(response.read())

2 个答案:

答案 0 :(得分:1)

致电decode(),将bytes解码为str

compressedFile.write(response.read().decode())

答案 1 :(得分:1)

您应该在将字节传递给写入函数

之前对其进行解码
compressedFile = StringIO()
compressedFile.write(response.read().decode("utf-8"))

另见the docs"utf-8"可能会被省略,因为它是默认值,但显式优于隐式; - )