Python 3.3 - urllib.request - import error

14,718

Solution 1

You named your file urllib, it is shadowing the standard library package. Rename your file.

Solution 2

In mac, VSCode is using Python 2. If you print urllib module, you will find out that this module is for Python 2.

So, I added one comment to choose Python version:

#!/usr/local/bin/python3
from urllib.request import urlopen
Share:
14,718
narzero
Author by

narzero

Updated on June 04, 2022

Comments

  • narzero
    narzero about 2 years

    When I try to run the following Python 3.3 code on OS X 10.8 in PyCharm 2.7 (or run the .py file with the Python 3.3/2.7.3 launcher):

    import urllib.request
    f = urllib.request.urlopen('http://www.python.org/')
    print(f.read(300))
    

    I get the following error message:

    /System/Library/Frameworks/Python.framework/Versions/3.3/bin/python3 /Users/username/PycharmProjects/urllib/urllib.py
    Traceback (most recent call last):
      File "<frozen importlib._bootstrap>", line 1512, in _find_and_load_unlocked
    AttributeError: 'module' object has no attribute '__path__'
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/Users/username/PycharmProjects/urllib/urllib.py", line 3, in <module>
        import urllib.request
      File "/Users/username/PycharmProjects/urllib/urllib.py", line 3, in <module>
        import urllib.request
    ImportError: No module named 'urllib.request'; urllib is not a package
    
    Process finished with exit code 1
    

    The only way I can succesfully run the code is via the Python shell.

    Any ideas on how to solve this?

    Thanks.


    I changed the filename to url.py, now it succesfully executes in PyCharm.

    But when executing the file via Python Launcher 3.3 it gives me the following error:

     File "/Users/username/PycharmProjects/urllib/url.py", line 3, in <module>
    import urllib.request
    ImportError: No module named request
    

    Why is the code running fine in PyCharm (3.3) but giving me an error when launched with Python Launcher (3.3)?