Import Script from a Parent Directory


How do I import a module(python file) that resides in the parent directory?

Both directories have a file in them but I still cannot import a file from the parent directory?

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

Folder A:
   Script A:
   Folder B:
     Script B(attempting to import Script A)

The following code in Script B doesn’t work:

import ../ # I get a compile error saying the "." is invalid
Asked By: sazr



From the docs:

from .. import scriptA

You can do this in packages, but not in scripts you run directly. From 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 for use as the main module of a
Python application should always use absolute imports.

If you create a script that imports A.B.B, you won’t receive the ValueError.

Answered By: Rob Wouters

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

  1. Add the FolderA’s path to the environment variable (PYTHONPATH).
  2. Add the path to sys.path in the your script.


import module_you_wanted
Answered By: capfredf

You don’t import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).

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

└── subpackage

In moduleB:

from toplevel_package import moduleA

If you’d like to run as a script then make sure that parent directory for toplevel_package is in your sys.path.

Answered By: jfs

I struggled same kind of issue, and published syspend module on PyPI
This searches parent directories which have specific named file, and calls sys.path.append(directory: which has SYSPEND_ROOT file).

Folder A:
   Script A:
   Folder B:
     Script B(attempting to import Script A)

In your case, please put SYSPEND_ROOT file. Empty file is OK.
In your

import syspend
import ScriptA

if __name__ == "__main__":
Answered By: town_paddy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.