简体   繁体   中英

regarding using urllib3 to replace urllib2

I was trying to use the following code segment. I am using Python 3, which has urllib3 instead of urllib2. I would like to know how replace this part fh = urllib2.urlopen('http://people.ku.edu/~gbohling/geostats/WGTutorial.zip') data = fh.read() in urllib3 . Thanks.

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 is part of urllib.request so you have to modify your imports:

from urllib.request import urlopen  

If you want your script to run in python 2 and python 3 you can use:

try:  
    from urllib2 import urlopen
except ImportError:  
    from urllib.request import urlopen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM