You seem to be adding path to mysite package, not Project1. But app1 is located in Project1, so Python can't find it.

Try this:

sys.path.append("/home/jack/workspace/Project1")
Answer from ovgolovin on Stack Overflow
🌐
Reddit
reddit.com › r/learnprogramming › why am i getting a module not found error even when i append the path ?
r/learnprogramming on Reddit: Why am I getting a Module not Found Error even when I append the path ?
September 11, 2023 -

I am not sure if maybe there is a problem because the name of the module is Module. However when I append it and I print the sys.path.append(). I see the file. When I append the path am I appending the actual file or the folder. I did both and they are still not working.

File where I want to export : \Refresh\Personal_Projects\PCEP\PCEP_pt2\Module\main1.py

Current File I'm in :\Refresh\Personal_Projects\PCEP\PCEP_pt2\Module\mod4.py

import sys

sys.path.append('D:\Refresh\Personal_Projects\PCEP\PCEP_pt2\Module')

from Module import main1

info = 'txt'
writeto(info) # writeto is the function within main1
ModuleNotFoundError: No module named 'Module'

Top answer
1 of 3
6

2 errors in your code:

  1. The Project directory is not just 1-level up. From the point of view of file1.py, it is actually 2 levels up. See this:
$ cd ..
(venv) nponcian 1$ tree
.
└── Project
    ├── folder1
    │   └── file1.py
    └── folder2
        └── file2.py
(venv) nponcian 1$ cd Project/folder1/
(venv) nponcian folder1$ ls ..
folder1  folder2
(venv) nponcian folder1$ ls ../..
Project
  1. Even if the above works, adding a relative path as a string would literally append that string as its raw value. So if you add a print(sys.path), it would display something like this:
['/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '../Project', '.']
  • It literally added '../Project', so if python started searching for the target modules in folder2, it wouldn't still find them because how would it know where exactly is '../Project' relative to.

Solution

What you need to add is the absolute path. If your problem is it might change, it is fine because we don't need a fixed absolute path. We can get the absolute path through the location of the current file being executed e.g. file1.py and then extracting the parent directory needed. Thus, this will work regardless if the absolute paths change because the way we are getting it is always relative to file1.py. Try this:

Project/folder1/file1.py

from pathlib import Path
import sys
sys.path.append(str(Path(__file__).parent.parent.parent))  # 1. <.parent> contains this file1.py 2. <.parent.parent> contains folder1 3. <.parent.parent.parent> contains Project

... the rest of the file
2 of 3
2

TL;DR

You can solve this by creating a setup.py file for your project and then running pip install -e ., instead of modifying sys.path.

Motivation

This answer might seem to come from left field for this question, but I'm putting it here because OP showed interest in this solution, and I think it's generally a preferable solution to mucking around with sys.path.

Details

The solution I tend to prefer for my projects is to create an actual setup.py for them, as if I was going to publish them to PyPI, and then run pip install -e . to have them actually installed in my (possibly virtual) python environment.

Here's a minimalist setup.py similar to one I used before:

from setuptools import setup

setup(
    name="project",
    version="0.0.1",
    python_requires=">=3.6",
    author="Some cool dude",
    long_description="Some cool project",
    install_requires=["dep1", "dep2"],
)

In another project, I read my requirements.txt file in my setup.py:

from setuptools import setup

with open("requirements.txt") as f:
    requirements = f.read().splitlines()

setup(
    name="project",
    version="0.0.1",
    python_requires=">=3.6",
    author="Some cool dude",
    long_description="Some cool project",
    install_requires=requirements,
)

With either solution, the setup.py file is sibling to my project directory (I use lowercase for my project names, always), both typically being at the root of my Git repo, or under a src subdirectory.

cd to the directory where setyp.py and project are, and run

pip install -e .

and now from anywhere, you can import project or its submodules and Python will find them.

Suggested reading

Lots more details can be found about setup.py files at setup.py examples?

🌐
GitHub
bic-berkeley.github.io › psych-214-fall-2016 › sys_path.html
Where does Python look for modules? — Functional MRI methods
As a crude hack, you can also put your code directory on the Python sys.path at the top of the files that need it: ... The simple append above will only work when running the script from a directory containing the code subdirectory. For example: $ mkdir another_dir $ cd another_dir $ python3 ../scripts/a_script_with_hack.py Traceback (most recent call last): File "../scripts/a_script_with_hack.py", line 4, in <module> import a_module ModuleNotFoundError: No module named 'a_module'
🌐
Reddit
reddit.com › r/learnpython › importerror: no module named x even when using sys.path.insert absolute path?
r/learnpython on Reddit: ImportError: No module named x even when using sys.path.insert absolute path?
June 9, 2017 -

How is this possible when the path is definitely correct

sys.path.insert(0, '/pyproj/ports/port_checker/port_checker.py')
from port_checker import get_free_port

Traceback (most recent call last):
  File "check_followers.py", line 34, in <module>
    from port_checker import get_free_port
ImportError: No module named port_checker
🌐
Stack Overflow
stackoverflow.com › questions › 77693318 › no-module-named-x-error-even-with-sys-path-append
python - "No module named X" error even with sys.path.append - Stack Overflow
To import a sibling module function you can use a relative import: # some_script.py from app.some_python import Test Test() ... Running some_script.py will yield an error: ImportError: attempted relative import with no known parent package · To get around the Error, use the sys.path approach to temporarily modify the Python path: # some_script.py import sys sys.path.append('../app') from app.some_python import Test Test()
🌐
Reddit
reddit.com › r/learnpython › can't import module from a new directory using sys.path.append
r/learnpython on Reddit: Can't import module from a new directory using sys.path.append
September 19, 2019 -

I am trying to run the module from my desktop and I tried to use sys.path. append to append the path to the list. But it throws an error.

C:\Users\KrishnamurthyKA\PycharmProjects\Strings\venv\Scripts\python.exe C:/Users/KrishnamurthyKA/.PyCharmCE2019.2/config/scratches/scratch.py

Traceback (most recent call last):

File "C:/Users/KrishnamurthyKA/.PyCharmCE2019.2/config/scratches/scratch.py", line 5, in <module>

import my_module as mm

ModuleNotFoundError: No module named 'my_module'

Process finished with exit code 1

Code:

import sys

sys.path.append(r"C:\Users\KrishnamurthyKA\Desktop\my_module")
import my_module as mm
courses = ['History','Math','Physics','CompSci']

index = mm.find_index(courses, 'Math')
print(index)
print(test)

print(sys.path)
Find elsewhere
🌐
YouTube
youtube.com › watch
Sys.path.append Module Not Found Error solve it python - YouTube
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
Published: May 9, 2020
🌐
Leemendelowitz
leemendelowitz.github.io › blog › how-does-python-find-packages.html
How does python find packages? // Lee On Coding // My blog about coding and stuff.
import sys, os # This won't work - there is no hi module import hi Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named hi # Create a hi module in your home directory. home_dir = os.path.expanduser("~") my_module_file = os.path.join(home_dir, "hi.py") with open(my_module_file, 'w') as f: f.write('print "hi"\n') f.write('a=10\n') # Add the home directory to sys.path sys.path.append(home_dir) # Now this works, and prints hi!
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.

🌐
Towards Data Science
towardsdatascience.com › home › programming › how to fix modulenotfounderror and importerror
How to Fix ModuleNotFoundError and ImportError | Towards Data Science
September 13, 2020 - In some rare cases, you might have to use relative imports in order to avoid unnecessarily long paths. For instance, ... Now we're up to speed with how the basic import statement is executed and what is the difference between absolute and relative imports we can now go ahead and discuss what to do when your Python application fails with either ModuleNotFoundError ** or** ImportError . In most of the cases, either of the errors occur due to the fact that Python is unable to resolve the module's name in sys.path .
🌐
iO Flood
ioflood.com › blog › python-no-module-named
[SOLVED] 'No Module Named' Python Error Solutions
January 30, 2024 - Here’s how: import sys ... path to your module is not in this list, you need to add it. You can do this by appending the path to sys.path like this:...
🌐
Stack Overflow
stackoverflow.com › questions › 73001862 › no-module-name-a-error-even-after-adding-the-path-to-sys-path
python - No module name A error even after adding the path to sys.path - Stack Overflow
Since you are running it from C folder that's why you are getting module not found error which is obvious. Try python C/a3.py from folder A. Your working directory should be the top level directory in your project files. Otherwise you will have to set your working directory as A before running python a3.py from folder C ... A is the grandmother for a2.py. Try to add it to sys.path · ROOT_PATH = pathlib.Path(__file__).parents[1] sys.path.append(os.path.join(ROOT_PATH, ''))
🌐
JetBrains
youtrack.jetbrains.com › issue › PY-27807 › Pycharm-not-recognizing-custom-module-name-that-imported-with-sys.path.append
Pycharm not recognizing custom module name that ...
Our website uses some cookies and records your IP address for the purposes of accessibility, security, and managing your access to the telecommunication network. You can disable data collection and cookies by changing your browser settings, but it may affect how this website functions.
🌐
Linux Hint
linuxhint.com › sys-path-append-python
How to Use Sys.path.append() in Python – Linux Hint
In other words, the current working directory is a member of the list of sys.path but “directory1” is not a member of that list. So, the resulting error is a ModuleNotFound Error – it couldn’t find or locate the module called file1. In order to avert this problem, you need to tell the Python interpreter where to look for the module file1. This is where the sys.path.append() method comes in.