Import a module from a relative path

How do I import a Python module given its relative path?

For example, if dirFoo contains Foo.py and dirBar, and dirBar contains Bar.py, how do I import Bar.py into Foo.py?

Here's a visual representation:

dirFoo\
    Foo.py
    dirBar\
        Bar.py

Foo wishes to include Bar, but restructuring the folder hierarchy is not an option.


Asked by: John427 | Posted: 01-10-2021






Answer 1

Assuming that both your directories are real Python packages (do have the __init__.py file inside them), here is a safe solution for inclusion of modules relatively to the location of the script.

I assume that you want to do this, because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter.

 import os, sys, inspect
 # realpath() will make your script run, even if you symlink it :)
 cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
 if cmd_folder not in sys.path:
     sys.path.insert(0, cmd_folder)

 # Use this if you want to include modules from a subfolder
 cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
 if cmd_subfolder not in sys.path:
     sys.path.insert(0, cmd_subfolder)

 # Info:
 # cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
 # __file__ fails if the script is called in different ways on Windows.
 # __file__ fails if someone does os.chdir() before.
 # sys.argv[0] also fails, because it doesn't not always contains the path.

As a bonus, this approach does let you force Python to use your module instead of the ones installed on the system.

Warning! I don't really know what is happening when current module is inside an egg file. It probably fails too.

Answered by: Dominik534 | Posted: 02-11-2021



Answer 2

Be sure that dirBar has the __init__.py file -- this makes a directory into a Python package.

Answered by: Blake434 | Posted: 02-11-2021



Answer 3

You could also add the subdirectory to your Python path so that it imports as a normal script.

import sys
sys.path.insert(0, <path to dirFoo>)
import Bar

Answered by: Kellan548 | Posted: 02-11-2021



Answer 4

import os
import sys
lib_path = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'lib'))
sys.path.append(lib_path)

import mymodule

Answered by: Lenny232 | Posted: 02-11-2021



Answer 5

Just do simple things to import the .py file from a different folder.

Let's say you have a directory like:

lib/abc.py

Then just keep an empty file in lib folder as named

__init__.py

And then use

from lib.abc import <Your Module name>

Keep the __init__.py file in every folder of the hierarchy of the import module.

Answered by: Miranda384 | Posted: 02-11-2021



Answer 6

If you structure your project this way:

src\
  __init__.py
  main.py
  dirFoo\
    __init__.py
    Foo.py
  dirBar\
    __init__.py
    Bar.py

Then from Foo.py you should be able to do:

import dirFoo.Foo

Or:

from dirFoo.Foo import FooObject

Per Tom's comment, this does require that the src folder is accessible either via site_packages or your search path. Also, as he mentions, __init__.py is implicitly imported when you first import a module in that package/directory. Typically __init__.py is simply an empty file.

Answered by: Julian550 | Posted: 02-11-2021



Answer 7

The easiest method is to use sys.path.append().

However, you may be also interested in the imp module. It provides access to internal import functions.

# mod_name is the filename without the .py/.pyc extention
py_mod = imp.load_source(mod_name,filename_path) # Loads .py file
py_mod = imp.load_compiled(mod_name,filename_path) # Loads .pyc file 

This can be used to load modules dynamically when you don't know a module's name.

I've used this in the past to create a plugin type interface to an application, where the user would write a script with application specific functions, and just drop thier script in a specific directory.

Also, these functions may be useful:

imp.find_module(name[, path])
imp.load_module(name, file, pathname, description)

Answered by: Haris440 | Posted: 02-11-2021



Answer 8

This is the relevant PEP:

http://www.python.org/dev/peps/pep-0328/

In particular, presuming dirFoo is a directory up from dirBar...

In dirFoo\Foo.py:

from ..dirBar import Bar

Answered by: Brad628 | Posted: 02-11-2021



Answer 9

The easiest way without any modification to your script is to set PYTHONPATH environment variable. Because sys.path is initialized from these locations:

  1. The directory containing the input script (or the current directory).
  2. PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  3. The installation-dependent default.

Just run:

export PYTHONPATH=/absolute/path/to/your/module

You sys.path will contains above path, as show below:

print sys.path

['', '/absolute/path/to/your/module', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']

Answered by: John493 | Posted: 02-11-2021



Answer 10

In my opinion the best choice is to put __ init __.py in the folder and call the file with

from dirBar.Bar import *

It is not recommended to use sys.path.append() because something might gone wrong if you use the same file name as the existing python package. I haven't test that but that will be ambiguous.

Answered by: Audrey621 | Posted: 02-11-2021



Answer 11

The quick-and-dirty way for Linux users

If you are just tinkering around and don't care about deployment issues, you can use a symbolic link (assuming your filesystem supports it) to make the module or package directly visible in the folder of the requesting module.

ln -s (path)/module_name.py

or

ln -s (path)/package_name

Note: A "module" is any file with a .py extension and a "package" is any folder that contains the file __init__.py (which can be an empty file). From a usage standpoint, modules and packages are identical -- both expose their contained "definitions and statements" as requested via the import command.

See: http://docs.python.org/2/tutorial/modules.html

Answered by: Clark568 | Posted: 02-11-2021



Answer 12

from .dirBar import Bar

instead of:

from dirBar import Bar

just in case there could be another dirBar installed and confuse a foo.py reader.

Answered by: Kate767 | Posted: 02-11-2021



Answer 13

For this case to import Bar.py into Foo.py, first I'd turn these folders into Python packages like so:

dirFoo\
    __init__.py
    Foo.py
    dirBar\
        __init__.py
        Bar.py

Then I would do it like this in Foo.py:

from .dirBar import Bar

If I wanted the namespacing to look like Bar.whatever, or

from . import dirBar

If I wanted the namespacing dirBar.Bar.whatever. This second case is useful if you have more modules under the dirBar package.

Answered by: Maya283 | Posted: 02-11-2021



Answer 14

Add an __init__.py file:

dirFoo\
    Foo.py
    dirBar\
        __init__.py
        Bar.py

Then add this code to the start of Foo.py:

import sys
sys.path.append('dirBar')
import Bar

Answered by: Lydia350 | Posted: 02-11-2021



Answer 15

Relative sys.path example:

# /lib/my_module.py
# /src/test.py


if __name__ == '__main__' and __package__ is None:
    sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
import my_module

Based on this answer.

Answered by: Stuart272 | Posted: 02-11-2021



Answer 16

Well, as you mention, usually you want to have access to a folder with your modules relative to where your main script is run, so you just import them.

Solution:

I have the script in D:/Books/MyBooks.py and some modules (like oldies.py). I need to import from subdirectory D:/Books/includes:

import sys,site
site.addsitedir(sys.path[0] + '\\includes')
print (sys.path)  # Just verify it is there
import oldies

Place a print('done') in oldies.py, so you verify everything is going OK. This way always works because by the Python definition sys.path as initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

Answered by: Dexter535 | Posted: 02-11-2021



Answer 17

Another solution would be to install the py-require package and then use the following in Foo.py

import require
Bar = require('./dirBar/Bar')

Answered by: Chelsea130 | Posted: 02-11-2021



Answer 18

Simply you can use: from Desktop.filename import something

Example:

given that the file is name test.py in directory Users/user/Desktop , and will import everthing.

the code:

from Desktop.test import *

But make sure you make an empty file called "__init__.py" in that directory

Answered by: Kimberly395 | Posted: 02-11-2021



Answer 19

Here's a way to import a file from one level above, using the relative path.

Basically, just move the working directory up a level (or any relative location), add that to your path, then move the working directory back where it started.

#to import from one level above:
cwd = os.getcwd()
os.chdir("..")
below_path =  os.getcwd()
sys.path.append(below_path)
os.chdir(cwd)

Answered by: Dexter348 | Posted: 02-11-2021



Answer 20

I'm not experienced about python, so if there is any wrong in my words, just tell me. If your file hierarchy arranged like this:

project\
    module_1.py 
    module_2.py

module_1.py defines a function called func_1(), module_2.py:

from module_1 import func_1

def func_2():
    func_1()

if __name__ == '__main__':
    func_2()

and you run python module_2.py in cmd, it will do run what func_1() defines. That's usually how we import same hierarchy files. But when you write from .module_1 import func_1 in module_2.py, python interpreter will say No module named '__main__.module_1'; '__main__' is not a package. So to fix this, we just keep the change we just make, and move both of the module to a package, and make a third module as a caller to run module_2.py.

project\
    package_1\
        module_1.py
        module_2.py
    main.py

main.py:

from package_1.module_2 import func_2

def func_3():
    func_2()

if __name__ == '__main__':
    func_3()

But the reason we add a . before module_1 in module_2.py is that if we don't do that and run main.py, python interpreter will say No module named 'module_1', that's a little tricky, module_1.py is right beside module_2.py. Now I let func_1() in module_1.py do something:

def func_1():
    print(__name__)

that __name__ records who calls func_1. Now we keep the . before module_1 , run main.py, it will print package_1.module_1, not module_1. It indicates that the one who calls func_1() is at the same hierarchy as main.py, the . imply that module_1 is at the same hierarchy as module_2.py itself. So if there isn't a dot, main.py will recognize module_1 at the same hierarchy as itself, it can recognize package_1, but not what "under" it.

Now let's make it a bit complicated. You have a config.ini and a module defines a function to read it at the same hierarchy as 'main.py'.

project\
    package_1\
        module_1.py
        module_2.py
    config.py
    config.ini
    main.py

And for some unavoidable reason, you have to call it with module_2.py, so it has to import from upper hierarchy.module_2.py:

 import ..config
 pass

Two dots means import from upper hierarchy (three dots access upper than upper,and so on). Now we run main.py, the interpreter will say:ValueError:attempted relative import beyond top-level package. The "top-level package" at here is main.py. Just because config.py is beside main.py, they are at same hierarchy, config.py isn't "under" main.py, or it isn't "leaded" by main.py, so it is beyond main.py. To fix this, the simplest way is:

project\
    package_1\
        module_1.py
        module_2.py
    config.py
    config.ini
main.py

I think that is coincide with the principle of arrange project file hierarchy, you should arrange modules with different function in different folders, and just leave a top caller in the outside, and you can import how ever you want.

Answered by: Daryl572 | Posted: 02-11-2021



Answer 21

This also works, and is much simpler than anything with the sys module:

with open("C:/yourpath/foobar.py") as f:
    eval(f.read())

Answered by: Adelaide458 | Posted: 02-11-2021



Answer 22

Call me overly cautious, but I like to make mine more portable because it's unsafe to assume that files will always be in the same place on every computer. Personally I have the code look up the file path first. I use Linux so mine would look like this:

import os, sys
from subprocess import Popen, PIPE
try:
    path = Popen("find / -name 'file' -type f", shell=True, stdout=PIPE).stdout.read().splitlines()[0]
    if not sys.path.__contains__(path):
        sys.path.append(path)
except IndexError:
    raise RuntimeError("You must have FILE to run this program!")

That is of course unless you plan to package these together. But if that's the case you don't really need two separate files anyway.

Answered by: Carlos929 | Posted: 02-11-2021



Similar questions

python relative import

This question already has answers here:


python - Relative import works on CLI but not in script

I addded the project root of my python project to the PYTHONPATH. Now the import of my modules works in the CLI of python bot NOT in a python script. How can I fix that?


python - Relative import in Django

I am currently developing a client/server application. Client and server are both Django projects. I would like to import client models in the server application. Here is the arborescence of my files : client/ fileapp/ __init__.py models.py ... client/ __init__.py ... manage.py server/ fileapp/ __init__.py views.py ... ...


Python - Relative import

I am developing a Python program where it manages and runs modules ( .py python files ) which can be added by users and are imported into the main program ( foo.py ) by using import function. Here's the directory structure Foo/ foo.py #Main script. Imports ouput.py, core.py and bar.py when needed. src/ __init__.py output.py #Output functions required by bar.py and foo.py core...


Python relative import fails in Maya

I am defining a new Python pipeline for Maya 2012 and I am having difficulty setting up package properly. I have: Prod __init__.py PackA __init__.py PAMod1.py PackB __init__.py PBMod2.py PAMod1 def a():pass PAMod2 def b():pass How do I call PAMod1.b in PAMod2.b? How do I...


Python import from relative path

On Python 2.7 I have the following: dir1/dir2/File1.py dir1/dir3/File2.py File2.py wants to import File1.py What are the non-hacky, pythonic, standard ways of doing this? dir1, dir2 and dir3 contain __init__.py


python - Relative import django models in views

May someone please give me complete explanation about how this works: While models.py and views.py are on the same directory on a django app, why should we use relative import: app1: models.py # my models was defined here views.py from .models import * # this works from app1.models import * # this also works from models import * # ---this one does not work ---


python - Relative import error with py2exe

I was trying to generate an executable for a simple Python script. My setup.py code looks like this: from distutils.core import setup import py2exe setup(console=["script.py"]) However, I am getting the error shown in the screenshot. Is there something I could try to fix this? I am using Windows 10.


Python 2.7 mock relative import

Background: Wanna build a documenation for a package, which imports a C-extension relatively, eg. in an __ init__.py. Lets assume this package is called mypkg.sub. So c_ext resides in sub. init.py of sub: from __future__ import absolute_import from . import c_ext When I mock this extension I do the following in my Sphinx conf.py: from mock import Mock sys.modules['m...


python - Relative Import Error

I am originally a Django developer and now I'm trying to play some basic and pure python OOP. I'm all good until I tried importing an abstract base class to be inherited on my child classes The error is: Traceback (most recent call last): File "inheritance.py", line 1, in &lt;module&gt; from . abstract_base_class import Vehicle ValueError: Attempted relative import in non-package ...


Python import from relative path error

I am trying to import from a relative path using sys.path.append My directories look like that: /main --run.py /tools --tool.py at main.py I'm having this code for importing tool.py: sys.path.append("../tools/") from tool import myFunc but when I run the code, get thin error: ImportError: No module name...


python - Import a module relative to a file path

I'm working on a macro engine that transforms YAML files. These YAML files contain paths to Python modules that I am importing using importlib. I would like for end users to be able to specify relative paths beginning with ., and for these paths to be resolved relative to the YAML file. (This way, a user could easily ship the YAML file and a related module in a directory or zip file.) I wo...


python - Relative import

I'm trying to make a dynamic relative import in Python but i'm not sure how to do it. My project is organized like this : . ├── __init__.py ├── requests.py └── serializers.py and I need to do the equivalent of from .serializers import Serializer. I tried multiple time with __import__, imp and importlib but I'm not even sure it's p...


python - Relative import error with flask

According to this, I am trying to run my flask web application from my com_profiler directory as python -m api.index, python -m api.index.py, python api/index.py


python - Relative import module

For a project: package\ │ └───┐ package\ │ ├──── __init__.py └───┐ subpackage\ │ ├──── __init__.py └──── spam.py in subpackage\__init__.py I can import spam via: from package.subpackage.spam import eggs, beans ...or... from .spam import...


Yet another Python Relative import mishap

#Background and Problem# I'm trying to build a web-scraper to back up my social media accounts (summer project, I know it's useless). I'm trying to create a nice class structure, so I've come up with the following structure (I accept critique, I'm pretty new to programming): \social-media-backup \Files __init__.py File.py Image.py Video.py \So...


python - How can I fix these relative import error

I have a folder structure like this, each time I attempt to use relative import, error raises ├── graphics │ ├── __init__.py │ ├── A │ │ ├── __init__.py │ │ ├── grok.py │ │ └── spam.py └── B ├── __init__.py └── bar.py spam.py/ def func(): pass bar.py/ def f(): pass All these codes are tested in grok.py: from . im...


python - Relative import works with from but fails with import

I need to use a relative import in python, so I do: from .MyModule import MyClass and it works :) However sometimes I don't want to explicitly import MyClass, but instead import MyModule and access my class by doing MyModule.MyClass So I would love to do: import .MyModule my_instance = MyModule.MyClass() ...


python - Import error using relative import syntax

I have a project structured like so: /proj main.py config/ __init__.py setup.py gui/ __init__.py app.py The program is run by calling python main.py. In main.py I have from gui import App. In gui/__init__.py I have from .app import App. Lastly, in app...


python - Relative import doesn't work for no reason

I've made a script and the user @eyllanesc literally just rewrote in a proper way, organizing it in three files (gui.py, cli.py and lib.py). The thing is that imports in gui.py and cli.py don't work. I've done res...


python - Specifying relative path in py2exe

When specifying my script file in setup.py, e.g. "script": 'pythonturtle.py', how can I specify its relative position in the file system? In my case, I need to go down two folders and then go into the "src" folder and it's in there. How do I write this in a cross-platform way?


python - Django relative urls and https

I have a Django project using https for certain part of the url (/account/, /admin/, /purchase/). When on one of this page in https mode, all the relative inner links {% url foo %} will point to https://my_url. However I do not want to have those pages shown as https :home, contacts ... What are the solutions for this kind of requirements ? Enfo...


Relative Python Path to Script

Python project looks like this: setup.py README Application scripts hello.py shell_scripts date.sh From hello.py I'm executing the command subprocess.call(['../shell_scripts/date.sh']) and receiving the error OSError: [Errno 8] Exec format error. Note: date.sh is a perfectly valid shell script and is executable. I've a...


python relative import

This question already has answers here:


python - Relative import works on CLI but not in script

I addded the project root of my python project to the PYTHONPATH. Now the import of my modules works in the CLI of python bot NOT in a python script. How can I fix that?


python - How to get text file from a relative path?

If I have a file directory like this: -Proj - Proj.py - Directory - input.txt and Proj.py wants to read from input.txt, how can I get to it? open() seems to only take an absolute address.


Python Filter List Items Relative to Each Other

Let's say I have a list of tuples: fruits = [('apple','red',23), ('apple','green',12), ('orange','small',12), ('orange','large',1)] How can I quickly and cleanly create a new list with the tuples that have the largest numbers but unique to fruit name. So the ideal result would be: fruits = [('apple','red',23), ('orange','small',12)]


python - How to mock using patch relative paths?

I have something like this in a python test file: from mock import patch, from ..monkey import ook [...] @patch('monkey.ook', Mock(return_value=None)) def test_run_ook (self, mock_ook): self.assertIsNone(ook()) mock_ook.run.assert_called_once_with('') When I run this test, I get a ImportError: No module named monkey. Clearly, the path I am patching is not right. Howe...


How to get relative file path on Python 2.5?

I was using python 2.6 for a script, but for requirement limitations I have to downgrade my script to python 2.5, how can I get the relative path using python 2.5? I was previously using: os.path.relpath(path[, start]) But since this is new from 2.6 I can't use it anymore. Thanks and regards!


python - A way to store relative dates in string form

I have a scheduler that will fire a task T, and some of the parameters to T are very dependent on the date. For example, if T is run on a Tuesday, some of the parameters would be: param1 = datetime('Monday at 1pm') param2 = datetime('Tuesday at 1am') The parameters can vary depending on when T is run. So, for example, if it's run on Sunday, the parameter...


python - Specifying relative path in py2exe

When specifying my script file in setup.py, e.g. "script": 'pythonturtle.py', how can I specify its relative position in the file system? In my case, I need to go down two folders and then go into the "src" folder and it's in there. How do I write this in a cross-platform way?


python - Find a path in Windows relative to another

This problem should be a no-brainer, but I haven't yet been able to nail it. I need a function that takes two parameters, each a file path, relative or absolute, and returns a filepath which is the first path (target) resolved relative to the second path (start). The resolved path may be relative to the current directory or may be absolute (I don't care). Here as an attempted implementation, complete with s...


How do I make these relative imports work in Python 3?

I have a directory structure that looks like this: project/ __init__.py foo/ __init.py__ first.py second.py third.py plum.py In project/foo/__init__.py I import classes from first.py, second.py and third.py and put them in __all__. There's a class...


python - Apply relative URL to an absolute URL

I have an absolute URL, and the URL that a link on that page points to. Is there a builtin function to apply a relative URL to an absolute URL? Ie. "http://example.com/some/url", "/some/url/I/want/to/go/to" => "http://example.com/some/url/I/want/to/go/to"


django - How can I specify a relative path in a Python logging config file?

I've the following file to config logging: [loggers] keys=root [handlers] keys = root [formatters] keys = generic # Loggers [logger_root] level = DEBUG handlers = root # Handlers [handler_root] class = handlers.RotatingFileHandler args = ("test.log", "maxBytes=1*1024*1024", "backupCount=10") level = NOTSET formatter = generic # Formatters [formatter_generic] format = %(asctime)s,%(msecs)03d %(levelname...


Python ctypes: loading DLL from from a relative path

I have a Python module, wrapper.py, that wraps a C DLL. The DLL lies in the same folder as the module. Therefore, I use the following code to load it: myDll = ctypes.CDLL("MyCDLL.dll") This works if I execute wrapper.py from its own folder. If, however, I run it from elsewhere, it fails. That's because ctypes computes the path relative to the current working direc...


python - How to fix broken relative links in offline webpages?

I wrote a simple Python script to download a web page for offline viewing. The problem is that the relative links are broken. So the offline file "c:\temp\webpage.html" has a href="index.aspx" but when opened in a browser it resolves to "file:///C:/temp/index.aspx" instead of "http://myorginalwebsite.com/index.aspx". So I imagine that ...


django - Problem with Python relative imports

I am using Python 2.6 and have the Facebook API installed as a python package (under /usr/lib64/python2.6/site-packages/facebook/...) which means, it is available with a plain import facebook or from facebook import .... This works well, as long as there is no name clash. For example, in my project, I try to import the Facebook API in my code at project.facebook with from ....


python - Doctest and relative imports

I'm having trouble using doctest with relative imports. The simple solution is just to get rid of the relative imports. Are there any others? Say I have a package called example containing 2 files: example/__init__.py """ This package is entirely useless. &gt;&gt;&gt; arnold = Aardvark() &gt;&gt;&gt; arnold.talk() I am an aardvark. """ from .A import Aardvark...


Relative imports in Python

Hey all -- I am pulling my hair out with relative imports in Python. I've read the documentation 30 times and numerous posts here on SO and other forums -- still doesn't seem to work. My directory structure currently looks like this src/ __init__.py main.py components/ __init__.py expander.py language_id.py utilities/ __init__.py functions.py ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top