How to Import Python File Again
Module
In Python, a module is a single unit of Python lawmaking that tin be imported (loaded and used) by other Python code. A module tin incorporate definitions (like functions and constants), too as statements that initialize those definitions. One time the module code is written, it can be reused by any script that imports the module.
A common fashion to create a Python module is to create a file with a filename that ends in .py
, and write the module code in there. If we use a different file extension in the filename, or no extension at all, the standard import
statements shown below will non piece of work, and we'll have to use importlib
instead, which requires more than code (more info below).
To illustrate standard import
usage, let'south say we create a file called mymodule.py
with the following role definition:
1 2 | def say_hello ( ) : print ( ' Hi, world! ' ) |
Now every fourth dimension we want to write "Hello, world!" to the screen from a Python script, nosotros can simply import this module rather than having to write the bulletin over again. It also allows united states of america to change one line of code inside mymodule.py
rather than in many different scripts if nosotros e'er decide to change the message we want to testify in all the scripts that employ this role.
Import a File in the Same Directory
Allow's say we take 2 Python files in the aforementioned directory:
myscripts/
mymodule.py
script.py
mymodule.py
contains the say_hello()
function nosotros saw in a higher place.
To telephone call say_hello()
from inside script.py
, we can write in script.py
:
ane two 3 | import mymodule mymodule . say_hello ( ) |
The name used in the import
statement is but the module'due south filename without the .py
extension at the end.
Import a File in a Subdirectory (Python 3.three and Upward)
Python versions iii.3 and higher permit easy imports of modules in subdirectories of the current script'south directory. If you're using a Python version lower than 3.3, you can follow the steps in Import a File in a Different Directory instead.
Let's say we move mymodule.py
to a subdirectory chosen subdir
:
myscripts/
subdir/
mymodule.py
script.py
Then if we're using Python 3.three or higher, we can write in script.py
:
1 ii 3 | import subdir . mymodule subdir . mymodule . say_hello ( ) |
In a file system path, nosotros would dissever the components of a path using /
(Linux, macOS, etc.) or \
(Windows). In a Python import
statement, however, nosotros separate the path components using a dot (.
).
We can also assign a shorter proper noun for the module using an import
-as
statement:
1 2 3 | import subdir . mymodule every bit chiliad m . say_hello ( ) |
where grand
is whatsoever proper noun we cull. We can also import the function directly:
1 two iii | from subdir . mymodule import say_hello say_hello ( ) |
This works even if in that location are multiple levels of subdirectories. For example, if we had the following directory structure:
myscripts/
alpha/
beta/
mymodule.py
script.py
we could write in script.py
:
1 2 3 | import alpha . beta . mymodule as mymodule mymodule . say_hello ( ) |
Import a File in a Different Directory
Now let's say that nosotros move mymodule.py
to a directory that is outside of the current directory tree:
/
blastoff/
beta/
mymodule.py
myscripts/
script.py
By default, Python looks for files in the same directory (including subdirectories) as the current script file, too as in other standard locations defined in sys.path
. If you're curious what these locations are, you can print out the sys.path
variable like this:
i 2 3 4 | import sys for p in sys . path : print ( p ) |
Withal, if the file we want to import is somewhere else entirely, we'll showtime have to tell Python where to look by adding search directories to sys.path
. In our instance, we tin can write in script.py
:
1 two iii 4 5 vi | import sys sys . path . append ( ' /alpha/beta ' ) import mymodule mymodule . say_hello ( ) |
Note that the path appended to sys.path
is an absolute path. If we used a relative path, the path would resolve differently based on the directory from which the user is running the script, not relative to script.py
's path.
To append a directory relative to this script file, y'all tin can use __file__
to go the current script'due south full path and build a full path to the import from there. In script.py
nosotros can write:
1 ii 3 4 v half-dozen 7 viii 9 | import os import sys script_dir = bone . path . dirname ( __file__ ) mymodule_dir = os . path . bring together ( script_dir , ' .. ' , ' alpha ' , ' beta ' ) sys . path . append ( mymodule_dir ) import mymodule mymodule . say_hello ( ) |
Import Whatever File, Including Non-.py
File Extension (Python 3.4 and Up)
Accented Path
Python versions iii.4 and college provide functionality through the built-in importlib
library that allows us to load any file anywhere as a Python module, fifty-fifty if the file's filename does not stop in .py
(it can take a different file extension, or no file extension at all).
For case, let's say we have the following directory structure:
/
alpha/
beta/
mymodule
myscripts/
script.py
Notice here that the mymodule
filename does not accept a file extension. In this case, we tin't employ a simple import
argument to import that file. Instead, we can write in script.py
:
ane ii 3 4 v vi 7 8 9 10 xi | import importlib . mechanism import importlib . util # Import mymodule loader = importlib . machinery . SourceFileLoader ( ' mymodule ' , ' /alpha/beta/mymodule ' ) spec = importlib . util . spec_from_loader ( ' mymodule ' , loader ) mymodule = importlib . util . module_from_spec ( spec ) loader . exec_module ( mymodule ) # Use mymodule mymodule . say_hello ( ) |
Note that the path passed into SourceFileLoader()
is an accented path. If we used a relative path similar ../blastoff/beta/mymodule
, the path would resolve differently based on the directory from which the user is running the script, not relative to script.py
's path.
Relative Path
If we want to reference a file relative to our current script file's path, we tin apply __file__
to offset become our current script file'south path, and then build a total path from there:
1 2 three 4 5 six 7 viii 9 10 eleven 12 thirteen 14 xv xvi | import importlib . mechanism import importlib . util from pathlib import Path # Get path to mymodule script_dir = Path ( __file__ ) . parent mymodule_path = str ( script_dir . joinpath ( ' .. ' , ' blastoff ' , ' beta ' , ' mymodule ' ) ) # Import mymodule loader = importlib . machinery . SourceFileLoader ( ' mymodule ' , mymodule_path ) spec = importlib . util . spec_from_loader ( ' mymodule ' , loader ) mymodule = importlib . util . module_from_spec ( spec ) loader . exec_module ( mymodule ) # Use mymodule mymodule . say_hello ( ) |
References
- The import system — Python 3 documentation
- "module" — Glossary — Python iii documentation
- importlib — Python iii documentation
-
importlib.machinery
usage example is based on the CPython interpreter source code.
garnettobarresidde95.blogspot.com
Source: https://csatlas.com/python-import-file-module/
0 Response to "How to Import Python File Again"
Post a Comment