How do I import other files in Python?
- How exactly can I import a specific python file like
import file.py
? - How can I import a folder instead of a specific file?
- I want to load a Python file dynamically at runtime, based on user input.
- I want to know how to load just one specific part from the file.
For example, in main.py
I have:
from extra import *
Although this gives me all the definitions in extra.py
, when maybe all I want is a single definition:
def gap():
print
print
What do I add to the import
statement to just get gap
from extra.py
?
You do not have many complex methods to import a python file from one folder to another. Just create a __init__.py file to declare this folder is a python package and then go to your host file where you want to import just type
from root.parent.folder.file import variable, class, whatever
To import a specific Python file at 'runtime' with a known name:
...
In case the module you want to import is not in a sub-directory, then try the following and run
app.py
from the deepest common parent directory:Directory Structure:
In
app.py
, append path of client to sys.path:Optional (If you load e.g. configs) (Inspect seems to be the most robust one for my use cases)
Run
This solution works for me in cli, as well as PyCharm.
Just to import python file in another python file
lets say I have helper.py python file which has a display function like,
Now in app.py, you can use the display function,
The output,
I'm working sundar gsv
NOTE: No need to specify the .py extension.
This may sound crazy but you can just create a symbolic link to the file you want to import if you're just creating a wrapper script to it.
importlib
is recent addition in Python to programmatically import a module. It just a wrapper around__import__
See https://docs.python.org/3/library/importlib.html#module-importlibUpdate: Answer below is outdated. Use the more recent alternative above.
Just
import file
without the '.py' extension.You can mark a folder as a package, by adding an empty file named
__init__.py
.You can use the
__import__
function. It takes the module name as a string. (Again: module name without the '.py' extension.)Type
help(__import__)
for more details.