0

I am a Python beginner, so please forgive the noob question. I read through similar questions already but cannot find a solution, as most point to a version issue in Python, which is not the case here as I am using 3.7.6.

I am doing an exercise with urllib and encountered the aforementioned error. In order to check if my code caused it, I ran a sample code from the course website:

import urllib.request

fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
for line in fhand:
    print(line.decode().strip())

Please note that 'urllib.py' is the file name where I stored this code locally.

This should return the contents of the text file and print them line by line. However, I get:

Traceback (most recent call last):
  File "urllib.py", line 1, in <module>
    import urllib.request, urllib.parse, urllib.error
  File "/Users/xxx/Documents/urllib.py", line 1, in <module>
    import urllib.request, urllib.parse, urllib.error
ModuleNotFoundError: No module named 'urllib.request'; 'urllib' is not a package

We tested the code on someone else's machine and it works just fine. Any ideas what could be causing this? Thanks!

Matthias
  • 123
  • 2
  • 7
  • 19
  • Looks like you are executing the code with Python2. Try `import sys;print(sys.version_info)` before the import. Or you have created a file of your own named 'urllib.py' – snakecharmerb Aug 15 '20 at 08:22
  • Thanks - actually the file name 'urllib.py' was created by me to store the code snippet. I will amend the question text to clarify. I am running version 3.7.6. – Matthias Aug 15 '20 at 08:25
  • 2
    Rename your 'urllib.py', it's preventing python from finding the standard library package. – snakecharmerb Aug 15 '20 at 08:27
  • That solved it, thanks a lot! Just to understand the issue better: can you explain how the file name where the code is stored impacts it? I want to make sure I understand the logic so I do not make the same mistake again in other situations. How does the Terminal interpret this? EDIT: I just found a similar explanation which solves it for me, so thanks again! – Matthias Aug 15 '20 at 08:31
  • 1
    It's explained in the first paragraph of the accepted answer to the linked duplicate: " The current directory is prepended to sys.path, so the local name takes precedence over the installed name" – snakecharmerb Aug 15 '20 at 08:33

0 Answers0