I have a Python module called my_module.py
in a folder ~/my_module
. I want to call this module from a Python interpreter and I don’t know its directory. I run:
import os
os.chdir(os.path.expanduser("~/my_module"))
import my_module
and it fails. But if I use from ... import ...
, then it works:
import os
os.chdir(os.path.expanduser("~/my_module"))
from my_module import my_module
If I change the folder’s name to be different from the module’s name, then the direct import works. Why is that?
5
Files in the folder are not available in the module by default.
When you type import xyz
in your code, one of two things can happen:
- There’s a file
xyz.py
, then this file will be imported - There’s a folder named
xyz
, then the file__init__.py
inside that folder will be imported
Other files than __init__.py
aren’t imported by default. If you want to keep your file structure like this, you should add a file __init__.py
in your my_module
folder and put the following content inside it:
from . import my_module
from .
means that python will look for the file in your current directory. Then, when calling import my_module
in your main file, my_module
will have an attribute my_module
which holds everything defined in my_module/my_module.py
.
(you should think about renaming this…)
However, this only makes sense if the my_module
folder is gonna hold multiple submodule files that do their stuff. If it’s just one important file, you should not try to import it from the my_module
folder, but rather put in one file and then add the folder where that file is to your path
using sys.path.append("path/to/whatever")
. os.chdir
is not the option of choice here.
Please tell me if anything is unclear