python how to import module from parent directory

Опубликовано: 06 Август 2026
на канале: CodeGrid
16
0

Download this code from https://codegive.com
Certainly! Importing modules from a parent directory in Python can be useful when you have a project structure with nested directories and you want to organize your code efficiently. Here's a step-by-step tutorial on how to import a module from a parent directory, along with code examples.
Let's assume you have the following project structure:
Create the following Python files with sample content:
parent_module.py (in parent_directory):
child_module.py (in child_directory):
Now, let's create the main_script.py in the project root:
Open a terminal and navigate to the project directory. Run the main_script.py:
You should see the following output:
Remember that modifying sys.path should be done carefully, and this method is suitable for small to medium-sized projects. For larger projects, consider using relative imports or turning your project into a package.
ChatGPT