关于使用 urllib3 替换 urllib2
regarding using urllib3 to replace urllib2
我正在尝试使用以下代码段。我正在使用 Python 3,它具有 urllib3
而不是 urllib2。我想知道如何在 urllib3
中替换这部分 fh = urllib2.urlopen('http://people.ku.edu/~gbohling/geostats/WGTutorial.zip')
data = fh.read()
。谢谢
clusterfile = 'ZoneA.dat'
if not os.path.isfile(clusterfile):
fh = urllib2.urlopen('http://people.ku.edu/~gbohling/geostats/WGTutorial.zip')
data = fh.read()
fobj = StringIO.StringIO(data)
myzip = zipfile.ZipFile(fobj,'r')
myzip.extract(clusterfile)
fobj.close()
fh.close()
In python 3 urlopen
是 urllib.request
的一部分,因此您必须修改导入:
from urllib.request import urlopen
如果您希望脚本在 python 2 和 python 3 中 运行,您可以使用:
try:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen
我正在尝试使用以下代码段。我正在使用 Python 3,它具有 urllib3
而不是 urllib2。我想知道如何在 urllib3
中替换这部分 fh = urllib2.urlopen('http://people.ku.edu/~gbohling/geostats/WGTutorial.zip')
data = fh.read()
。谢谢
clusterfile = 'ZoneA.dat'
if not os.path.isfile(clusterfile):
fh = urllib2.urlopen('http://people.ku.edu/~gbohling/geostats/WGTutorial.zip')
data = fh.read()
fobj = StringIO.StringIO(data)
myzip = zipfile.ZipFile(fobj,'r')
myzip.extract(clusterfile)
fobj.close()
fh.close()
In python 3 urlopen
是 urllib.request
的一部分,因此您必须修改导入:
from urllib.request import urlopen
如果您希望脚本在 python 2 和 python 3 中 运行,您可以使用:
try:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen