Working With Files And Directories
Python 3 comes with a module called os, which stands for “operating system.” The os module contains a plethora of functions to get information on — and in some cases, to manipulate — local directories, files, processes, and environment variables. Python does its best to offer a unified api across all supported operating systems so your programs can run on any computer with as little platform-specific code as possible.
The current working directory
When you’re just getting started with Python, you’re going to spend a lot of time in the Python Shell. Throughout this book, you will see examples that go like this:
- Import one of the modules in the examples folder
- Call a function in that module
- Explain the result
There is always a current working directory.
If you don’t know about the current working directory, step 1 will probably fail with an ImportError
. Why? Because Python will look for the example
module in the import search path, but it won’t find it because the examples
folder isn’t one of the directories in the search path. To get past this, you can do one of two things:
- Add the
examples
folder to the import search path - Change the current working directory to the
examples
folder
The current working directory is an invisible property that Python holds in memory at all times. There is always a current working directory, whether you’re in the Python Shell, running your own Python script from the command line, or running a Python cgi script on a web server somewhere.
The os
module contains two functions to deal with the current working directory.
Get hands-on with 1400+ tech skills courses.