Mainland
Mainland

Reputation: 4564

Python No module found error while importing .py from another folder

I have followed a wildly accepted answer, which did not work for me. Here is what I have: Folder structure:

Demo folder

enter image description here

Fold1

enter image description here

Fold2

enter image description here

Also, the __init__.py is an empty file. Has nothing in it.

Objective: import customfunction.py file from Demo or Fold1 into Fold2

Code in MainFile.py:

import pandas as pd
import Demo.customfunctions

Output:

ModuleNotFoundError: No module named 'Demo'

Upvotes: 0

Views: 720

Answers (1)

radekholy24
radekholy24

Reputation: 417

All you need is a proper combination of your current working directory, the PYTHONPATH environment variable, and the path to the script.

If your current working directory is Downloads, you can run the Demo.Fold2.MainFile module without modifying PYTHONPATH. I.e.

> python -m Demo.Fold2.MainFile

Or you can run the Demo\Fold2\MainFile.py file if you set PYTHONPATH to the current working directory. I.e.

> :: relative PYTHONPATH
> set PYTHONPATH=.
> python Demo\Fold2\MainFile.py
>
> :: or absolute PYTHONPATH
> set PYTHONPATH=c:\absolute\path\to\Downloads
> python Demo\Fold2\MainFile.py

If your current working directory is Demo, you can run the Fold2.MainFile module if you set PYTHONPATH to the Downloads directory. I.e.

> :: relative PYTHONPATH
> set PYTHONPATH=..
> python -m Fold2.MainFile
>
> :: or absolute PYTHONPATH
> set PYTHONPATH=c:\absolute\path\to\Downloads
> python -m Fold2.MainFile

or the Fold2\MainFile.py file. I.e.

> :: relative PYTHONPATH
> set PYTHONPATH=..
> python Fold2\MainFile.py
>
> :: or absolute PYTHONPATH
> set PYTHONPATH=c:\absolute\path\to\Downloads
> python Fold2\MainFile.py

If your current working directory is Fold2, you can run the MainFile module if you set PYTHONPATH to the Downloads directory. I.e.

> :: relative PYTHONPATH
> set PYTHONPATH=..\..
> python -m MainFile
>
> :: or absolute PYTHONPATH
> set PYTHONPATH=c:\absolute\path\to\Downloads
> python -m MainFile

or the MainFile.py file. I.e.

> :: relative PYTHONPATH
> set PYTHONPATH=..\..
> python MainFile.py
>
> :: or absolute PYTHONPATH
> set PYTHONPATH=c:\absolute\path\to\Downloads
> python MainFile.py

Upvotes: 1

Related Questions