pythonmacospython-3.10modulenotfounderrorfile-location

Python Module not found ONLY when .py file is on desktop


Only for a .py file that is saved on my Desktop, importing some modules (like pandas) fail due to Module not found from an import that happens within the module. This behaviour doesn't happen when the file is saved to a different location.

Working on a Mac and i made a test.py file that only holds: import pandas as pd

when this test.py is saved on my desktop it generates this error:

Desktop % python3 test.py
Traceback (most recent call last):
  File "/Users/XXX/Desktop/test.py", line 2, in <module>
    import pandas as pd
  File "/Users/XXX/Desktop/pandas/__init__.py", line 22, in <module>
    from pandas.compat import (
  File "/Users/XXX/Desktop/pandas/compat/__init__.py", line 15, in <module>
    from pandas.compat.numpy import (
  File "/Users/XXX/Desktop/pandas/compat/numpy/__init__.py", line 7, in <module>
    from pandas.util.version import Version
  File "/Users/XXX/Desktop/pandas/util/__init__.py", line 1, in <module>
    from pandas.util._decorators import (  # noqa
  File "/Users/XXX/Desktop/pandas/util/_decorators.py", line 14, in <module>
    from pandas._libs.properties import cache_readonly  # noqa
  File "/Users/XXX/Desktop/pandas/_libs/__init__.py", line 13, in <module>
    from pandas._libs.interval import Interval
ModuleNotFoundError: No module named 'pandas._libs.interval'

the weird thing is that if i save the test.py file to any other location on my HD it imports pandas perfectly. Same thing happens for some other modules. The module im trying to import seems to go oke but it fails on an import that happens from within the module.

running which python3 in console from either the desktop folder or any other folder results in: /Users/XXXX/.pyenv/shims/python

python3 --version results in Python 3.10.9 for all locations.


Solution

  • You have a directory named pandas on your desktop.

    Python trying to import from this directory instead of the global package named pandas.

    You can also see that in the exception, look at the trace, from /Users/XXX/Desktop/test.py the code moves to /Users/XXX/Desktop/pandas/__init__.py and so on.

    Just rename the name of the directory on your desktop. For your own safety, you should not name your local directories with the same names as global packages.