What is the current path when python import module?

Jimmy (xiaoke) Shen
1 min readSep 22, 2022

--

Original I thought the current path is the path where you run the python code. Such as python ./subfloder/XX.py, then the current path will be the previous path of subfloder.

However, I am wrong. It should be the folder of the XX.py which is the subfolder. Let’s verify by an example.

Two files used in the example

this_is_a_test├── hello_world.py└── say_hello_world.py

hello_world.py

def hello_world():print("hello world!")

say_hello_world.py

from hello_world import hello_worldhello_world()

First simple run (success)

Under the folder of this_is_a_test, run. Correct.

this_is_a_test % python say_hello_world.pyhello world!

Second run (success)

What about the following command when run the code at the previous folder of “this_is_a_test” folder?

% python this_is_a_test/say_hello_world.pyhello world!

It works, then it means, when importing, the python is looking for the package in the current folder of the to be executed folder, which is this_is_a_test ,instead of the “CURRENT FOLDER”, which is the previous path of this_is_a_test.

Third run (fail)

In order to verify, we move the hello_world.py code to the previous path of this_is_a_test folder and run

this_is_a_test % python say_hello_world.pyhello world!

Got the following error:

% python this_is_a_test/say_hello_world.pyTraceback (most recent call last):File "this_is_a_test/say_hello_world.py", line 1, in <module>from hello_world import hello_worldModuleNotFoundError: No module named 'hello_world'

By those 3 tests, we can see that the python is looking for the subfloder when you run the code. The subfolder is this_is_a_test.

python this_is_a_test/say_hello_world.py

--

--

No responses yet