Python OS Module
Introduction
As a Python programmer, we don't want to navigate our mouse to the folders to complete our tasks. What do we want? We want to type a command and have it perform all of the tasks easily and efficiently. So here comes the idea of using the OS module, which will allow us to operate and interact with the system more simply.
This module helps users by giving methods to interact with the directories/folders within the script and allowing us to do various operations on the directory such as creating the directory, removing the directory, retrieving the content, identifying the directory, and so on.
To execute any of the above operations, we first import the OS module by using import statement that is:
"import os".
After that, we can access all of the os module's functions. Let’s see more details about this module.
Handling the Current Work Directory
If you want to work with files that are present in different directories, always use the absolute path. The absolute path provides the exact location of that file or directory related to the root directory. On the other hand, if you are working on a current directory (CWD), then we call any file/folder by its name.
For example: If you are currently working on the Downloads folder, and there is a folder called Data in the downloads folder, and you want to fetch all the data. Since you are in the downloads folder, then you need to provide the whole path like C:\Users\Dell\Downloads\Data. But if you are already in the Data folder, here comes the concept of relative path, which means you only need to call the file by its name.
The function “os.getcwd()” is used to get the current working directory. This will return the absolute path to our working directory as a string. Here getcwd stands for Get Current Working Directory.
Let’s see the example:
Output:
So I executed the code, and it returns the current directory, which in my case is Dell.
Note:
Current directory is the folder in which the python script is executing. Like in my case the Python script file is saved in the “C:\Users\Dell” directory of my laptop. So when I use the getcwd() function it will print the “C:\Users\Dell”.
Changing the Current Directory
In python for changing the directory ‘os.chdir()’ method is used, this function changes the directory path to the specified one. It just takes a new path as an argument. Here chdir stands for Change Directory.
Let’s see some examples to change your current working directory:
Example 1:
Output:
So I have changed the current path of the script from Dell to Desktop by just passing the absolute path (C:\Users\Dell\OneDrive\Desktop) as an argument to the ‘os.chdir()’ function.
Note:
“r” is called Raw String in Python. This is useful when we want to have a string with a backslash in it but don't want it to be considered as an escape sequence.
Suppose, I write “Scaler\nAcademy” inside the print function.Where \n is the escape character representing next line.
Output:
But, if I use ‘r’ in the given string, let’s see what happen:
Output:
It will not consider \n as escape character.
Example 2:
Output:
So I have changed the current path of the script from Dell to direct Users folder by just passing ‘../’ as an argument to the ‘os.chdir()’ function.
Note:
“../” symbol is used to go one directory above.**
Creating a Directory
In Python, the ‘os.mkdir()’ function is used to create a directory (Folder). Inside the ‘os.mkdir’ function we have to just pass a path as an argument where you want to create a directory. Here mkdir stands for Make Directory.
Output:
Now let’s say I wanna create a folder inside a folder that doesn’t exist, so it will throw a FileNotFoundError error.
Example:
Output:
In the above example, we can see that we are trying to create a folder called Scaler Content and InterviewBit inside the Temp folder, but the Temp folder does not exist on the computer. So it will throw FileNotFoundError.
Functions in OS Module
The OS module is a module that contains several functions that are used to execute OS-related tasks. We have already discussed mostly used functions above, and from there we can realize how useful they are. So let’s discuss some more OS module functions in detail.
- os. name(): This function tells the name of the operating system that is currently working on your pc. In my case, it is showing ‘nt’ (new technology) , which is a graphical OS created by Microsoft.
Output:
- os.rmdir(): rmdir stands for Remove Directory. This function is used to delete the directory present in the system. It just needs the name or path of the directory that has to be deleted as its parameter. If it gets successfully deleted then it returns nothing but returns an error if it fails to delete that directory.
So, in the above code we have removed the Scaler Content folder. Now again we will try to remove it and let’s see what error will occur.
This will throw FileNotFoundError, because we have already deleted it before.
Output:
- os.rename(): This function is used to rename a file or directory. It just takes two arguments one is the source file path whose name is to be changed and another is the destination path to which name will be changed. Also if a file or directory exists with the same name as the destination OSError will be thrown.
Output:
Before:
After:
- os.error(): It produces an OSerror when there are invalid or inaccessible file names, directories, or parameters that the operating system does not allow.
Output:
- os.popen(): This technique creates a pipe to or from a command. Depending on whether the mode is 'r' or 'w,' the return value can be read or written.
Suppose, I created a text file and wrote anything in it, such that when I execute the script, nothing is open. If I use the popen function, the file window will open, and we will be able to see our content.
Output:
Now, I’ll be using the popen function and let’s see what happens?
Output:
- os.close(): It is used to close the given file descriptor so that it no longer links to any file or other resource. A file descriptor is a small integer value that represents a file or another type of input/output resource, such as a pipe or network socket.
If we open a file using the open() function then it can be closed using close() only, and if we try to close it using os.close() then it will through an error, and if we open a file using popen() function then we can close it using close() as well as os.close() function.
Output:
-
os.access(): With the help of uid/gid, It checks whether the user has access to file path or not.
-
Checking whether file path exists or not.
Output:
- Checking whether the OS has access to read files or not.
Output:
- Checking whether the OS has access to write on files or not.
Output:
- Check if the path can be executed.
Output:
Conclusion
As a result, we can conclude that the OS module in Python works as a link between a user and an operating system. This module provides us with a portable means of interacting with the operating system as well as functions to do so.
This module includes features that allow us to quickly do operations such as reading paths, removing files, renaming files, and so on. We have seen all the major functions of the OS module in the article.