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

Question:

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.

Asked By: Paul

||

Answers:

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.

Answered By: Emanuel

The issue may be related to Desktop folder permission, check this

https://support.apple.com/en-gb/guide/mac-help/mchld5a35146/mac

From the article

Choose Apple menu  > System Settings, then click Privacy & Security in the sidebar. (You may need to scroll down.)

Click Files and Folders.

For each app in the list, turn the ability to access files and folders in specific locations on or off.

You should be able to select permissions for Desktop folder as in this example

enter image description here