Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import a Python script from a sibling directory?

Let's say I have the following directory structure:

parent_dir/     foo_dir/         foo.py     bar_dir/         bar.py 

If I wanted to import bar.py from within foo.py, how would I do that?

like image 697
Orcris Avatar asked Apr 22 '12 22:04

Orcris


People also ask

How can we import .py file from another directory?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.

Can import Python file from same directory?

Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory". The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation.

Can you import from parent directory Python?

Python3. As we have discussed earlier it is not possible to import a module from the parent directory, so this leads to an error something like this.


2 Answers

If all occurring directories are Python packages, i.e. they all contain __init__.py, then you can use

from ..bar_dir import bar 

If the directories aren't Python packages, you can do this by messing around with sys.path, but you shouldn't.

like image 195
Sven Marnach Avatar answered Oct 05 '22 09:10

Sven Marnach


You can use the sys and os modules for generalized imports. In foo.py start with the lines

import sys import os sys.path.append(os.path.abspath('../bar_dir')) import bar 
like image 42
prrao Avatar answered Oct 05 '22 10:10

prrao