Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
7 views
in Python by (20.3k points)

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

Both directories have a __init__.py 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:

   __init__.py

   Script A:

   Folder B:

     __init__.py

     Script B(attempting to import Script A)

The following code in Script B doesn't work:

import ../scriptA.py # I get a compile error saying the "." is invalid

2 Answers

0 votes
by (40.7k points)

You shouldn't import scripts in Python but, you can 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 like this:

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 then make sure that parent directory for toplevel_package is in your sys.path.

0 votes
by (106k points)

To import script from a parent directory if you want to run the script directly, you can follow the steps mentioned below:-

  1. Add the folder's path to the environment variable (PYTHONPATH).

  2. Add the path to sys.path in your script.

Then:

import module_you_wanted

Related questions

0 votes
1 answer
asked Jul 10, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
0 votes
1 answer
asked Jun 26, 2019 in Python by Anurag (33.1k points)
0 votes
1 answer
asked Jan 7, 2021 in SQL by Appu (6.1k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...