Python3 Utilities: os module
May 24, 2019
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,
### 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
## Importing only the getcwd function from os module ##
from os import getcwd
curr_path = getcwd()
print(curr_path)
Introduction to os
module
OS Module is the collection of operating system dependent utilities in python. It allows us to interact with the underlying operating system in which python is running on. Let us look at some of the common operations performed using OS module.
os.path
Path submodule from OS module, provides the functions related to the file system path.
A file has two key properties
- Filename
- File path
File path denotes the location of the file in the operating system.
The path format differs between the operating systems, such as Windows system uses backslash while the Linux and Mac OS uses the forward slashes.
Lets look at our previous example
## Importing only the getcwd function from os module ##
from os import getcwd
curr_path = getcwd()
print(curr_path)
The above is the full path of the current directory in which the file is present. Since it is a Linux/MacOS system, the file path is separated by forward slashes.
The same path representation in Windows system would be as follows
C:\\home
Each of the slashes denotes the hierarchy of the directory structure.
os.path.join()
The join method in os.path sub module which allows the manipulation of the os independent directory handling. Based on the OS the python is running the join method will either append the paths with a forward slash or backward slash.
For instance, let obtain a full path for list of filenames:
import os
myfiles = ['file_1.py', 'file_2.py', 'file_3.py']
for i in myfiles:
print(os.path.join(os.getcwd(), i))
Let’s test your understanding on file paths.
os.listdir()
listdir method returns the list of directories present in the given path. The path argument is optional while the current directory will be taken as default when given with no arguments.
import os
print(os.listdir())
This returns only the available directories in current path and not the files or any sub directories in hierarchy.
os.mkdir()
mkdir method creates a directory in the specified path with the name as provided in argument.
import os
print(os.listdir())
os.mkdir('misc')
print(os.listdir())
As you can see, the directory misc
is now present in the output.
os.path.isfile()
isfile method checks if the given path is a file and if it exists. It returns boolean to denote either exists or not. True denotes the file exist while false denotes the given path is not a file or it may not exists
import os
# Check if jdoodle.py is present in the current path
print (os.path.isfile('jdoodle.py'))
# Check if file_1.py is present in the path
print (os.path.isfile('/home/file_1.py'))
Notice the path can be either absolute path or relative path
If you notice from our previous examples, the file with name jdoodle.py
is already present while the file_1.py
is not.
os.remove()
This method removes the file path.
import os
# List the content of directory
print(os.listdir('.'))
# Removing the file
os.remove('jdoodle.py')
# List the contents after removal
print(os.listdir('.'))
As expected, the file jdoodle.py
was removed.
Let’s test your understanding of the various methods we discussed above.
Summary
To recap, in this tutorial, you learned:
- Usage of import statement
- Basics of
os
module - Listing files and directories in the path
- Creating new directory and moving directories
- Checking if file exist in path
- Removing file from path