OS module provides a lot of functions to interact with Operating System which can handle files, processes and environment paths and many more.
If you are planning to automate some tasks in your server which handle paths, system variables OS module is the best option because of platform independence.
OS module is platform independent, you can write the script in any machine (Linux, Windows etc.) and you can execute the same script for the same functionality in other machines also if the code is not platform independent.
If you want to list down all functions for OS modules you can directly go through the official documentation page of python i.e https://docs.python.org/2/library/os.html.
Here I will discuss some of the functions which I use most of the time.
For any module in python, the first thing is you need to import it, and you can import os modules as below.
Retrieve and display all files and folders in the current working directory
To achieve this we can use
os.listdirfunction. By defaultOS module will take the current working directory as the location the execution is started, For exampleif you have created a python script in your Desktop with OS module and when you execute that program in Desktop it will take Desktop as CWD.
So just call
os.listdir('.'),it will print a list of all files and folders in a given path which I have given i.e '.'. You can change the path to anyexisting path and it will print like
To get current environment details you can use
if you want to get particular environment values
os.getenv(key) # key can be like PWD, PATH etc.
Handle with pathusing python os
One of the most useful moduleis os.path, it will construct paths like basesystem you are executing.
For example to get the absolute path of the current working directory we can give os.path.abspath('.'), it will give full path with/ or \based on operating system.
cur_path = os.path.abspath('.') # cur_path = '/home/kishore/'
fil_path = os.path.join(cur_path, 'file.txt')
print fil_path # It will print /home/kishore/file.txt in Linux environment whereas in windows it will print C:\Users\Kishore\file.txt
More Examples on os module
To execute commands directly we can use
os.system(command). To change the directory and execute there
With os module we can platform, tmpfile and so many useful scripts can be implemented without depending on platform.
If you find any interesting and useful code samples please post in this platform or comment below and we will update here.