Current Working Directory

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 earlier, 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, a script is always launched from the CWD, 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.

CWD, Files, and Import Paths

When you run a Python script by typing a shell command line such as python dir1\dir2\file.py, the 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 its module search path:

C:\PP3rdEd\Examples\PP3E\System>type whereami.py import os, sys print 'my os.getcwd =>', os.getcwd( ) # show my cwd ...

Get Programming Python, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.