The notion of the current working directory (CWD) turns out to be a
key concept in some scripts’ execution: it’s always the
implicit place where files processed by the script are assumed to
reside, unless their names have absolute directory paths. As we saw
os.getcwd lets a script fetch the CWD
name explicitly, and
os.chdir allows a script to
move to a new CWD.
Keep in mind, though, that filenames without full pathnames map to the CWD, and have nothing to do with your PYTHONPATH setting. Technically, the CWD is always where a script is launched from, not the directory containing the script file. Conversely, imports always first search the directory containing the script, not the CWD (unless the script happens to also be located in the CWD). Since this distinction is subtle and tends to trip up beginners, let’s explore it in more detail.
When you run a Python script by typing a shell command line like
CWD is the directory you were in when you typed this command, not
dir1\dir2. On the other hand, Python
automatically adds the identity of the script’s home directory
to the front of the module search path, such that
file.py can always import other files in
dir1\dir2, no matter where it is run from. To
illustrate, let’s write a simple script to echo both its CWD
and module search path:
type whereami.pyimport os, sys print 'my os.getcwd =>', os.getcwd( ) # show ...