Import Script from the parent directory

How to import a module (python file) that is in the parent directory?

There is a __init__.py file in both directories, but I still cannot import the file from the parent directory?

In this layout, the Script B folder is trying to import Script A:

 Folder A: __init__.py Script A: Folder B: __init__.py Script B(attempting to import Script A) 

The following code in Script B does not work:

 import ../scriptA.py # I get a compile error saying the "." is invalid 
+67
python import
Jan 21 2018-12-12T00:
source share
3 answers

You do not import scripts in Python, you import modules. Some python modules are also scripts that can be run directly (they do some useful work at the module level).

In general, it is preferable to use absolute imports rather than relative imports.

 toplevel_package/ ├── __init__.py ├── moduleA.py └── subpackage ├── __init__.py └── moduleB.py 

In moduleB :

 from toplevel_package import moduleA 

If you want to run moduleB.py as a script, make sure the parent directory for toplevel_package is in your sys.path .

+66
Jan 21 2018-12-12T00:
source share

From docs :

 from .. import scriptA 

You can do this in packages, but not in scripts that you run directly. By the link above:

Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always “__main__”, modules intended to be used as the main module must always use absolute import for the Python application.

If you create a script that imports ABB, you will not get a ValueError.

+26
Jan 21 '12 at 6:50
source share

If you want to run the script directly, you can:

  • Add the FolderA path to the environment variable ( PYTHONPATH ).
  • Add the path to sys.path in the script.

Then:

 import module_you_wanted 
+4
Jan 21 2018-12-12T00:
source share



All Articles