0
votes

There are two folders , each contain a python file . For example: first_folder contains a.py & second_folder contains b.py

I tried importing b.py in a.py But i got not Import error.

ImportError: No module named b

Pls help me to solve this. I also tried creating a blank init.py in both folders, but it did not worked.

Folder structure:

/home/user/scripts/

 |
 |--------python_scripts
 |          |
 |          |
 |          |------- a.py
 |
 |--------lib
           |
           |-------b.py
3
Could you provide an example of your folder structure?Daniel Butler
Probably these two files are not in the PATH or your working directory is not at the correct location.BcK
What is your folder structure and what files do you have in which folders?Bill Armstrong
first folder :'python_script' that contains a.py 2nd folder : ' lib ' that contains b.py Both folders are in same location. I am running the scripts one folder behind the locationLearner
For example: 'scripts ' folder contains ' python_script ' and ' lib' folder. i am executing in 'scripts' locationLearner

3 Answers

0
votes

Python's import is going to look for the modules (.py files) in the python path. You can see what is in python path in the sys.path variable.

By default, sys.path will include directory where the script you ran is located. It will also include everything defined in the PYTHONPATH environment variable.

So, if you have two directories with .py files, you can either put both in python path, or you can make sure everything all of your source is under the same path entry.

Option 1

(this syntax depends on your shell, here it is for windows)

set PYTHONPATH=%PYTHONPATH%;\path\to\second_folder

python \path\to\first_folder\a.py

Then, you can simply import b.

Option 2

Create an empty __init__.py in both directories and a run.py in the directory above them, so you have:

root_dir
    run.py
    first_folder
        __init__.py
        a.py
    sedond_folder
        __init__.py
        b.py

Make run.py your entry point (run python run.py) and then you can import any of the modules from any other module using their full module names:

import first_folder.a
import second_folder.b
0
votes

If the files are in the same directory type this

Import .other_file
0
votes

Suppose you have files like this

.
├── first_folder
│   └── a.py
└── second_folder
    └── b.py

You can use abs path to import a.py as a module in b.py

import importlib.util

spec = importlib.util.spec_from_file_location('a', 'path/to/first_folder/a.py')

foo = importlib.util.module_from_spec(spec)

spec.loader.exec_module(foo)

print(dir(foo))

There is another convenient way to load b.py

$ cd path/to/second_folder

$ ln -s path/to/first_folder ./first_folder

and import a.py as a normal python module

import a from first_folder