Example Modules
We will now look at how to use existing modules provided by the Python Standard Library.
Let’s explore one module that you may find useful: the os
module.
Before we start, I would like you to launch a new interactive Python prompt for this guided tutorial.
Now, let us examine our current namespace, which is essentially the list of names/variables/identifiers that you can currently use. If you type in the below, you should see a list of variables/identifiers, mostly with underscores.
>>> dir()
Now let us introduce a new variable x
. Then check the namespace again. You will find that x
has now been added to the namespace.
>>> x = 5
>>> dir()
Let’s now import
the os
module.
>>> import os
Now check dir()
again. You should see that os
has been added to the current namespace. This means that you can now use the module.
Let investigate further to really understand what os
really is.
>>> type(os)
>>> os
You may have noticed that os
is a module (a module
class if you want to be precise), and that it is loaded from a file os.py
somewhere on your Python installation path. Remember: modules are essentially scripts called module_name.py
.
If you want, you can take a look at the list of functions and classes offered by this module with help(os)
.
We will now try to use one of the functions defined in this module.
>>> os.listdir(".")
This should return a list of files from your current directory.