Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: is the current directory automatically included in path?

Tags:

Python 3.4: From reading some other SO questions it seems that if a moduleName.py file is outside of your current directory, if you want to import it you must add it to the path with sys.path.insert(0, '/path/to/application/app/folder'), otherwise an import moduelName statement results in this error:

ImportError: No module named moduleName 

Does this imply that python automatically adds all other .py files in the same directory to the path? What's going on underneath the surface that allows you to import local files without appending the Python's path? And what does an __init__.py file do under the surface?

like image 737
AllTradesJack Avatar asked Jun 26 '14 16:06

AllTradesJack


People also ask

Is current directory in Pythonpath?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .

How do I get the current path in Python?

How to Get Current Python Directory? To find out which directory in python you are currently in, use the getcwd() method. Cwd is for current working directory in python. This returns the path of the current python directory as a string in Python.

What is the default file path in Python?

When we run the graphical Python Shell, the current working directory starts as the directory where the Python Shell executable is. On Windows, this depends on where we installed Python; the default directory is c:\Python32.


1 Answers

Python adds the directory where the initial script resides as first item to sys.path:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

So what goes on underneath the surface is that Python appends (or rather, prepends) the 'local' directory to sys.path for you.

This simply means that the directory the script lives in is the first port of call when searching for a module.

__init__.py has nothing to do with all this. __init__.py is needed to make a directory a (regular) package; any such directory that is found on the Python module search path is treated as a module.

like image 106
Martijn Pieters Avatar answered Jan 22 '23 06:01

Martijn Pieters