This is what I use:

import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
Answer from jterrace on Stack Overflow
Discussions

Appending paths relative to the current file to sys.path - Post.Byes
Out of interest, are there any standard Python modules that do this: def appendRelativeI ncludePath(*rel path): dir = os.path.abspath (os.path.join(o s.path.dirname( __file__), *relpath)) if not dir in sys.path: sys.path.append (dir) I ask because I often find myself doing this: ---- # ... More on post.bytes.com
🌐 post.bytes.com
improving sys.path.append situation
Instead of modifying sys.path, you should set up your project so that the default sys.path happens to contain all the paths you need. The most important part of doing this is that you have to install you dependencies. Installing a package is basically the process of moving the necessary files to one of the directories listed on the default sys.path. You can install things with pip even if they're not publicly available through PyPI. Write a setup.py for your private packages and install them with something like pip install path/to/package. The second thing is that you need to pay attention to your entry points. You should not run any code directly inside your package. If you have code in your package that you want to run then you need to make sure that the script that is running it is outside of your package. The most direct way to do this is to have a script like run.py or something which just imports your package and runs it, but a better long term solution is to set put entry_points in your setup.py. You can also use python's -m flag to run package files as though they were scripts and it will take care of setting everything up (python -m my_package.my_submodule). You'll want to make sure you're using virtual environments to keep everything isolated. More information on packaging can be found on the official website for python packaging . If you're having trouble with any of this then it would help if you gave us more details about your project; its dependencies and how it's laid out. More on reddit.com
🌐 r/learnpython
4
4
November 3, 2018
Importing from a relative path in Python - Stack Overflow
I have a folder for my client code, a folder for my server code, and a folder for code that is shared between them Proj/ Client/ Client.py Server/ Server.py Common/ ... More on stackoverflow.com
🌐 stackoverflow.com
Cannot import relative python paths
Hello, Some variations of this question have been asked before but there doesn't seem to be an answer for the following simple use case: I have the following file structure on a Databricks Asset Bundles project: src --dir1 ----file1.py --dir2 ----file2.py There doesn't seem to be a way to import ... More on community.databricks.com
🌐 community.databricks.com
3
1
May 6, 2024
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί what does sys.path.append(".") do?
r/learnpython on Reddit: what does sys.path.append(".") do?
May 1, 2020 -

I have a structure like this:

Parent_Folder
-- foo.py
    Child_Folder_1
    -- bar.py
    -- egg.py
    Child_Folder_2
    -- spam.py

I tried relative importing on bar.py,

from ..import foo

but it did not work for reasons, and I somehow found a way to do this via internet.

import sys
sys.path.append(".")

now I can import foo.py and egg.py and even spam.py on bar.py, but I wonder how this is working, and what did that single line do. I've searched the web, but I doubt I found any understandable answers, so I'm posting this question here.

Since I'm not a professional at neither python nor programming, a kind explaination would be welcome :D Anyway, thanks for your time for reading this.

🌐
Datasciencebyexample
datasciencebyexample.com β€Ί 2024 β€Ί 01 β€Ί 16 β€Ί add-relative-path-to-system-in-python
Add relative path to system path in Python | DataScienceTribe
When runing pyton scripts, in order to import function from some file, we need to make sure that file is in the system path. So we can add a path in the code. While adding absolute path is easy, but it may not importable to other people. So here we show an example, where I want to add a relative path of 3 levels up than the file that’s being current running:
🌐
Learnings
ankursingh.hashnode.dev β€Ί learnings β€Ί #python β€Ί the hitchhiker's guide to `sys.path`
The Hitchhiker's Guide to `sys.path` - Learnings
May 3, 2022 - To make imports relative to cc.py file, we should append __file__ variable to our sys.path. __file__ is a special variable, in fact all double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.
🌐
Post.Byes
post.bytes.com β€Ί home β€Ί forum β€Ί topic β€Ί python
Appending paths relative to the current file to sys.path - Post.Byes
Out of interest, are there any standard Python modules that do this: def appendRelativeI ncludePath(*rel path): dir = os.path.abspath (os.path.join(o s.path.dirname( __file__), *relpath)) if not dir in sys.path: sys.path.append (dir) I ask because I often find myself doing this: ---- # myproject/lib/mymodule/test/test.py if __name__ == '__main__': import os.path import sys dir = os.path.abspath (os.path.join(o s.path.dirname( __file__), '..', '..')) if not dir in sys.path: sys.path.append (dir) import mymodule # it's always 2 directories up from here ---- And it seems like a lot to type so often.
🌐
GitHub
gist.github.com β€Ί justinmklam β€Ί c453ea62b47f4e302dbd83c05882e3bd
Techniques for python path manipulation and relative imports in (i.e. when not dealing with a package). Β· GitHub
Alternative to the above (good for multiple paths): import sys, os currentdir = os.path.dirname(__file__) srcdirs = ['../../path1', '../path2'] for src in srcdirs: sys.path.insert(0, os.path.abspath(os.path.join(currentdir, src)))
Find elsewhere
🌐
Linux find Examples
queirozf.com β€Ί entries β€Ί python-imports-reference-and-examples
Python Imports: Reference and Examples
April 25, 2020 - Similar to the above but get path with os.path.abspath(<relative-path>) and then use sys.path.insert(0, <path>) so that you can import from a relative directory: ... myproject/ β”œβ”€β”€ helpers β”‚ └── mymodule.py β”œβ”€β”€ utils β”‚ └── myothermodule.py └── stuff └── ...
🌐
Note.nkmk.me
note.nkmk.me β€Ί home β€Ί python
Check and Add the Module Search Path in Python: sys.path | note.nkmk.me
May 12, 2023 - Be aware that if there is a file with the same name as a standard library in the same directory as the executed script file, Python will import that file instead. Since sys.path is essentially a list, you can easily add new paths. In this example, the append() method is used, but you can also use the insert() method or other list methods.
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί improving sys.path.append situation
r/learnpython on Reddit: improving sys.path.append situation
November 3, 2018 -

I see my code is breaking due to possible overuse of sys.path.append. I'm working with lots of repositories and building libraries for me and others, so I have to pass relative path in this function. I'm comming from javascript, what's best practice with this when it comes ot python? As far as came this was the best thread.

I asked this on Python reddit and got following answer from jwink3101:

But anyway, you have to be more clear. At the top of your script, you do not want to do:

sys.path.append('/path/to/dir') 

unless you will only ever run it once and non-interactively. Instead do:

if '/path/to/dir' not in sys.path:     sys.path.append('/path/to/dir') 

But, really, you do not want to work this way. You should install what you need, make virtualenv's etc. (with that said, I do this too!)

################

I had to move it to this subreddit.

So in essence I have few of my private packages which I can't put on pip etc. and I'm tired of using sys.path.append because my path gets completely ruined. What's alternative in my case? For example, a lot of times I have to import ../someModule.py ,but isn't sys.path.append bad practice?

Top answer
1 of 4
4
Instead of modifying sys.path, you should set up your project so that the default sys.path happens to contain all the paths you need. The most important part of doing this is that you have to install you dependencies. Installing a package is basically the process of moving the necessary files to one of the directories listed on the default sys.path. You can install things with pip even if they're not publicly available through PyPI. Write a setup.py for your private packages and install them with something like pip install path/to/package. The second thing is that you need to pay attention to your entry points. You should not run any code directly inside your package. If you have code in your package that you want to run then you need to make sure that the script that is running it is outside of your package. The most direct way to do this is to have a script like run.py or something which just imports your package and runs it, but a better long term solution is to set put entry_points in your setup.py. You can also use python's -m flag to run package files as though they were scripts and it will take care of setting everything up (python -m my_package.my_submodule). You'll want to make sure you're using virtual environments to keep everything isolated. More information on packaging can be found on the official website for python packaging . If you're having trouble with any of this then it would help if you gave us more details about your project; its dependencies and how it's laid out.
2 of 4
1
The short answer is yes that’s what you have to do. It’s hacky and there are cleaner ways. But to long answer is here: https://m.youtube.com/watch?v=0oTh1CXRaQ0 I am a Beazley disciple so I am compelled to say you should watch any/all of his videos.
🌐
CodeRivers
coderivers.org β€Ί blog β€Ί sys-path-append-python
Understanding `sys.path.append` in Python - CodeRivers
February 22, 2026 - import sys sys.path.append('/home/user/projects/my_modules') import some_module Β· Relative Path: A relative path is relative to the current working directory.
🌐
CodeRivers
coderivers.org β€Ί blog β€Ί python-sys-path-append
Python `sys.path.append`: An In - Depth Exploration - CodeRivers
February 22, 2026 - In this example, we assume that there is a directory named my_custom_modules in the same directory as the script. By appending this relative path to sys.path, we are telling Python to look in this directory for modules.
🌐
Linux Hint
linuxhint.com β€Ί sys-path-append-python
How to Use Sys.path.append() in Python – Linux Hint
The current working directory is the directory in which the main python script – the one being executed – is found. Further, what this also means is that this list can be modified or edited. The sys.path.append() method is used specifically to add a Path to the existing ones.
Top answer
1 of 3
171

How python finds its modules

Strictly taken, a module is a single python file, while a package is a folder containing python files, accompanied by a (can be empty) file named __init__.py, to tell python it is a package to import modules from. In both cases, modules need their .py extension, but importing them is done without (see further below).

By default, Python looks for its modules and packages in $PYTHONPATH.

To find out what is included in $PYTHONPATH, run the following code in python (3):

import sys
print(sys.path)

How to add a directory

Occasionally

From within a python file, you can add path(s) occasionally to the default path by adding the following lines in the head section of your python application or script:

import sys
sys.path.insert(0, "/path/to/your/package_or_module")

For example:

if I have a folder: /home/myname/pythonfiles, and I want to import the file module_1.py, located in that directory, I add this to the head section of my code:

import sys
sys.path.insert(0, "/home/myname/pythonfiles")

And I can simply import the file module_1.py by:

import module_1

When I create a package and want to import module(s) from the package, I need to create a folder in $PYTHONPATH, containing the modules, accompanied by a (can be empty) file called __init__.py

For example:

To import from a package (folder) called my_package in /home/myname/pythonfiles , add the /home/myname/pythonfiles path to your $PYTHONPATH, like in example 1, and import the module called module_2.py (inside the package folder) simply with: `

from <packagename> import module_2

Adding directories to $PYTHONPATH permanently:

Add the following line to your ~/.profile file.

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

Subdirectories

From within a package, subdirectories are not included just like that; you need to "chain" the directories. To import a module module_3.py, inside folder subfolder inside folder packagename:

import packagename.subfolder.module_3

Given the fact that all subfolders in the package include their own __init__.py file.

When a module is in the same directory as the script or application

There is no need to insert the path to a module when it is in the same directory as the script or application, it is automatically added.

Example:

If I have a folder, containing script.py and module.py, I can simply import the module by:

import module
2 of 3
7

The correct way to use relative import is:

from ..Common import foo1

And you also need a __init__.py in all your folders.

Top answer
1 of 3
228

EDIT Nov 2014 (3 years later):

Python 2.6 and 3.x supports proper relative imports, where you can avoid doing anything hacky. With this method, you know you are getting a relative import rather than an absolute import. The '..' means, go to the directory above me:

from ..Common import Common

As a caveat, this will only work if you run your python as a module, from outside of the package. For example:

python -m Proj

Original hacky way

This method is still commonly used in some situations, where you aren't actually ever 'installing' your package. For example, it's popular with Django users.

You can add Common/ to your sys.path (the list of paths python looks at to import things):

import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))
import Common

os.path.dirname(__file__) just gives you the directory that your current python file is in, and then we navigate to 'Common/' the directory and import 'Common' the module.

2 of 3
13

Funny enough, a same problem I just met, and I get this work in following way:

combining with linux command ln , we can make thing a lot simper:

1. cd Proj/Client
2. ln -s ../Common ./

3. cd Proj/Server
4. ln -s ../Common ./

And, now if you want to import some_stuff from file: Proj/Common/Common.py into your file: Proj/Client/Client.py, just like this:

# in Proj/Client/Client.py
from Common.Common import some_stuff

And, the same applies to Proj/Server, Also works for setup.py process, a same question discussed here, hope it helps !

🌐
Safjan
safjan.com β€Ί home β€Ί note β€Ί adding parent directory to python path
Adding Parent Directory to Python Path - Krystian Safjan's Blog
May 28, 2024 - To add a parent directory to the Python path, you can use the following code: ... This code imports the sys module and then uses the insert() method to add the parent directory (indicated by '..') to the beginning of the sys.path list.
🌐
Databricks Community
community.databricks.com β€Ί databricks community β€Ί data engineering β€Ί cannot import relative python paths
Solved: Cannot import relative python paths - Databricks Community - 68275
May 6, 2024 - I have tried appending os.abspath("..") and "../.." to sys.path, as well as passing ${workspace.file_path} to the task and appending that, to no avail. Note that relative imports on the same level work so the following both work: # src # --file1.py # --file2.py # We are on file1.py from file2 import something # src # --file1.py # --dir2 # ----file2.py # We are on file1.py from dir2.file2 import something Β·
🌐
Medium
medium.com β€Ί tech-with-x β€Ί python-path-management-tips-for-handling-imports-efficiently-part-1-b8876fe33271
Python Path Management: Tips for Handling Imports Efficiently: Part 1 | by Xavier Alexander | Explained By X | Medium
June 3, 2024 - This happens because Python sets the current working directory to the directory containing the script and adds it to sys.path. As a result, import statements are relative to the script's directory.
🌐
Python.org
discuss.python.org β€Ί python help
Sys.path.append .. libdir multiple level causes error in PyCharm - Python Help - Discussions on Python.org
March 4, 2022 - Hi forum, The following snippets of two cases runs on system console terminal. The ver 1 runs in PyCharm. I do not know why ver 2 reports error in PyCharm. Thanks # ver 1. ok # myapp.py: import sys sys.path.append('..') from libdir import mylib mylib.hello() # ver 2. PyCharm: ModuleNotFoundError: ...