1

I am trying to import from relative path in my python program.

the class i would like to import is in

home/foo/bar/model.py 

However, my current python script is in

home/best/user/test.py

i have tried to use

from ../../foo/bar import class

But it throws up a syntax error

2 Answers 2

2

When importing modules, python looks in the current working directory and in the paths in sys.path. You can add the directory of the script you would like to import to sys.path:

import sys
sys.path.append('home/foo/bar')
import model # imports home/foo/bar/model.py
Sign up to request clarification or add additional context in comments.

Comments

2

You can't do that. You can't import from an explicitly specified path (without awful trickery). All Python imports are based on the systemwide import paths (in sys,path). You can't import anything that isn't reachable from sys,path (i.e., it's either on sys.path itself or it's inside a package that's on sys.path). The documenation has the details. If you want to be able to import from that file, you need to somehow add its directory (or the directory of its topmost containing package) to the path.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.