Q:

python - urllib.request.urlretrieve throws unexpected exception unknown url type: ' '

I am trying to download files using urllib.request.retrieve()
I am using Python 3 and the downloads are successful, but I don't know why it throws exception. 
For some reason it throws an exception. 
This is the main file:
import os
import urllib.request

zip_file_open = open("urls.txt")

if not os.path.exists('zip'):
    os.makedirs('zip')

num=1

true = True
b = true    

for i in zip_file_open.read().splitlines():
    try:
        print(str(i))
        #response = urllib.request.urlopen(str(i))
        #print(response)
        #html = response.read()
        urllib.request.urlretrieve(i, "zip/code"+str(num)+".zip")
        if(b):
            num+=1
            b=False
        else:
            b=true
    except Exception as e:
        print("Exception: "+str(e))
        if(b):
            num+=1
            b=False
        else:
            b=true

This is urls.txt:    
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c01_code.zip
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c02_code.zip
........
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c25_code.zip
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c26_code.zip

Here is how I create the txt file:
f = open("urls.txt","w")

k = """http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c"""
k1 = """_code.zip"""

import os

for i in range(26):
    if(i<9):
        f.write(k+str(0)+str(i+1)+k1+os.linesep)
    else:
        f.write(k+str(i+1)+k1+os.linesep)
f.close()

Here is the output
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c01_code.zip

Exception2: unknown url type: ''
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c02_code.zip

Exception3: unknown url type: ''
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c03_code.zip
Exception3: HTTP Error 404: Not Found

........

Exception26: unknown url type: ''
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c26_code.zip

Exception27: unknown url type: ''

I didn't include all the lines of output as they were same.  The code is functional but I would like to know if we can remove the exception. 

A:

It looks like you have some blank lines in your file, so urllib throws a ValueError exception when you try to fetch '', which is clearly not a url. 
You can fix this error if you add a condition in the loop to check for empty strings.   
for i in zip_file_open.read().splitlines(): 
    if not i.strip(): 
        continue
    ...

But this won't work for non-empty strings that are not urls, for example 'not a url'. 
A better approach would be to check the url scheme with urlparse. 
for i in zip_file_open.read().splitlines(): 
    if not urllib.parse.urlparse(i).scheme: 
        continue
    ...

