In this tutorial, we will discuss some general concepts on OS Module in Python3.
Import Statement
Before we read about the os module, let’s look at importing of code from one module to another in python. Though there are multiple ways for doing the same, the most common way is to use the import statement.
Import statement handles two major operations:
- Search for the named module
- Binding the results of named module to a local scope
This allows the modules to have their own copy of functions / variables without any conflict with other modules, although they may have the same name.
The import allows to either import the complete module or to even allow importing a specific function of the module.
For instance,
type=codeblock|id=python_import_1|autocreate=python3|show_output=1### Importing the os module ###import os## Assigning the current path to a local variable ###curr_path = os.getcwd()print(curr_path)
In here, the entire os module is imported and the specific function is invoked from os module using dot (.) operator.
The above method works, yet in order to use one function, the entire os module is imported. This can be avoided using specific imports such as below
type=codeblock|id=python_import_2|autocreate=python3|show_output=1## Importing only the getcwd function from os module ##from os import getcwdcurr_path = getcwd()print(curr_path)