Jeremy Barnes
Jeremy Barnes

Reputation: 662

How to import python module from different directory, same level, but different folder

I have a directory structure like

Documents/
    Project_1/
        module_1.py
    Project_2/
        module_2.py

If I want to import module_1.py into module_2.py, what is the syntax for it?

I have tried variations on

import ../Project_1/module_1

And

from .Project_1 import module_1

But I can't get it to work and have only done this once before in another project.

Upvotes: 0

Views: 1674

Answers (2)

Jeremy Barnes
Jeremy Barnes

Reputation: 662

It is a crude solution, but I ended up with something like this:

#This thing modifies the path
from sys import path

#This gets our user directory
from os import environ

#add module_1's location to path
path.append(environ['USERPROFILE'] + "\\Documents\\Project_1")

#import it now
import module_1

This is not the most elegant solution, but it can work on almost any Windows machine, assuming the folders are placed in their Documents.

The code about Environ could be reasonably replaced to match another directory, though.

Upvotes: 1

John
John

Reputation: 86

You have two alternatives;

from Documents.project_1 import module1.py

or

import Documents.project_1.module1.py

Upvotes: 1

Related Questions