Table of contents
1.
Introduction
2.
What is the OS library in Python?
3.
Functions In OS Module in Python
4.
Current Working Directory
5.
Change The Current Working Directory
6.
Create a Directory
6.1.
os.mkdir()
6.1.1.
Example 1: without specifying the path.
6.1.2.
Example 2: when the path is specified.
6.2.
os.makedirs()
6.2.1.
Example:
7.
Delete a Directory Or  Files
7.1.
os.remove()
7.2.
os.rmdir()
7.3.
os.removedirs()
7.3.1.
Example:
8.
Rename a Directory
8.1.
Example:
9.
Contents Of Directory
9.1.
os.name
9.2.
os.path
9.2.1.
os.path.join()
9.2.2.
os.path.basename()
9.2.3.
os.path.isdir()
9.2.4.
os.path.exists()
9.3.
os.error
9.4.
os.popen()
9.5.
os.close()
9.6.
os.rename()
9.7.
os.remove()
10.
Frequently Asked Questions
10.1.
Is os a standard Python library?
10.2.
Is os a package or module?
10.3.
How to make os in Python?
10.4.
What is the os module in the Python programming language?
10.5.
How can we use the os module in Python?
10.6.
Is the os module inbuilt in Python?
10.7.
Which function allows you to see the current working directory?
10.8.
Which is the common type of exception which is thrown in the os module?
11.
Conclusion
Last Updated: Jan 15, 2025
Easy

OS Module In Python

Author ANKIT KUMAR
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The os module provided in Python provides various functions through which we can do certain tasks that are done by the operating system. Tasks like creating a directory, deleting a directory, changing the directory, etc can be done very easily. There are various functions that are provided in this module. We shall see most of them in this article.

OS Module In Python

But as we have already learned, in order to use any module in Python, we should first import that module. The same has to be done while using the os module. We can simply use the import keyword to import the os module.

import os

What is the OS library in Python?

The os library in Python is a standard module that provides functions for interacting with the operating system. It acts as a bridge between Python programs and the underlying OS, enabling developers to perform tasks like file and directory manipulation, environment variable management, and process handling. The library is platform-independent, meaning it works across Windows, macOS, and Linux, adapting commands to the specific OS.

Functions In OS Module in Python

There are various functions that are available in the os module. Let's learn about some of them and their use.

  1. Current Working Directory
  2. Change The Current Working Directory
  3. Create a Directory
  4. Delete a Directory Or  Files
  5. Rename a Directory

Current Working Directory

The current working directory (CWD) is the folder where Python is currently running in the system. Whenever we try to call the file by just its name without specifying the path, Python actually searches the file in the current working directory.

In order to get the location of the current working directory in the system, we use the getcwd() function.

import os
currDir= os.getcwd()
print("The current working directory is :", currDir)

Output: 

The current working directory is : C:\Users\Ankit\PycharmProjects\osmoduleblog

Change The Current Working Directory

We can also change the current working directory using the os.chdir() function provided in the os module. If we try to access any file in the program after changing the directory, it will throw an error since its path has been changed, and the program will always try to search the file in the current working directory if the full path of the file is not given.

Code to change the directory:

import os
print(os.getcwd())
os.chdir(“C://”)
print(os.getcwd())

Output: 

C:\Users\Ankit\PycharmProjects\osmoduleblog
C:\

Create a Directory

We can create a new directory using the os.mkdir() function and the os.makedirs() function of the os module. 

os.mkdir()

Example 1: without specifying the path.

import os
os.mkdir("newdirectory")

This will create a new directory (folder) in the current working directory since the path is not provided in the string.

Example 2: when the path is specified.

import os
os.mkdir("C:/Users/new directory")

This will create a new directory inside the Users folder.

os.makedirs()

The os.makedirs() function is used to create subdirectories along with the 

Directory.

Example:

import os
os.makedirs(“folder1/folder2”)

The above code will create a folder with the name "folder1" and a subfolder inside folder1 with the name "folder2."

Delete a Directory Or  Files

os.remove()

Using the above function, we can delete a file by providing either the absolute or relative path. The function is used to delete only a file and not a directory. An attempt to delete a directory will throw OSError.

import os
os.remove("demofile.txt")

os.rmdir()

This function is used to delete an empty directory. Attempting to delete a non-empty directory will throw an error. We can provide either the absolute or the relative path of the directory that has to be deleted. The function will not delete the current working directory.

import os
os.rmdir("C:/Users/Ankit/PycharmProjects/dir1")

os.removedirs()

This function is used to delete the subdirectories along with the directory.

Example:

import os 
path=r"D:\sample\Test\1\2\3\4\5\6\7\8\9"
os.removedirs(path)

Rename a Directory

We can rename a file or a directory using the os.rename() function of the os module in Python. To rename a file or a directory, it must have the exact name as specified in the function. 

Example:

import os 
os.rename("initialDir","changedDir")

The above code will change the name of “initialDir” directory to “changedDir.”

Contents Of Directory

We can fetch the contents of any directory using the os.listdir() function. It returns the list of all the files and directories in the specified directory. If any specific directory is not provided, it returns the list of files and directories in the current working directory.

Example 1:

import os 
os.listdir()

Output: 

['.config', '.dotnet', 'python']

 

Example 2:

import os
os.listdir("/")

Output: 

['sys', 'run', 'tmp', 'boot', 'mnt', 'dev', 'proc', 'var', 'bin', 'lib64', 'usr', 
'lib', 'srv', 'home', 'etc', 'opt', 'sbin', 'media']

os.name

It is used to get the name of the imported operating system-dependent module. We don't use () in the name. 

import os
print(os.name)

Output: 

posix

os.path

We can perform various path-related tasks using the functions present in the os.path.

os.path.join()

This method is used to join various paths with exactly one directory separator (“/”).

Example:

import os
path="C:/Users/Ankit"
newPath= os.path.join(path,"newFile")
print(newPath)

Output: 

C:\Users\Ankit\newFile

os.path.basename()

This function will return the base name in the path specified.

Example:

import os
path="C:/Users/Ankit/Python/project1"
base_name= os.path.basename(path)
print(base_name)

Output: 

‘project1’

os.path.isdir()

This function is used to verify whether there exists a directory in the path provided or not. It returns true if there is a directory in the specified path. Otherwise, it returns false.

Example:

import os
path="C:/Users/Ankit/Python/project1"
res= os.path.isdir(path)
print(res)

Output :

True

os.path.exists()

This function returns true if the path provided is correct and exists. Otherwise, it returns false.

Example:

import os
path="D:/Users/Aman/Python/project1"
res= os.path.exists(path)
print(res)

 

Output: 

False

os.error

os.error is an alias for the built-in OSError exception in Python. It is raised when an operating system-related error occurs, such as file not found, permission denied, or invalid file descriptors. For example, attempting to delete a non-existent file will raise an OSError.

os.popen()

os.popen() opens a pipe to or from a command. It runs the specified command in a subshell and returns a file-like object that can be used to read or write data to the command’s standard input or output.

Example:

output = os.popen('ls').read()  # Executes the 'ls' command and captures the output
print(output)

os.close()

os.close() closes a file descriptor that was opened with low-level OS functions like os.open(). It releases the resource and makes the file descriptor invalid.

Example:

fd = os.open('example.txt', os.O_RDWR)  # Open a file
os.close(fd)  # Close the file descriptor

os.rename()

os.rename() renames a file or directory from one name to another. Both the source and target must exist in the same directory.

Example:

os.rename('old_name.txt', 'new_name.txt')  # Renames 'old_name.txt' to 'new_name.txt'

os.remove()

os.remove() deletes a file from the filesystem. If the file does not exist, an OSError is raised.

Example:

os.remove('file_to_delete.txt')  # Deletes the specified file

Frequently Asked Questions

Is os a standard Python library?

Yes, os is a standard Python library that provides functions to interact with the operating system, available by default in any Python installation.

Is os a package or module?

os is a module in Python, not a package. It provides a collection of functions for interacting with the operating system.

How to make os in Python?

You don’t "make" os in Python, as it’s a built-in module. Simply import it with import os to use its functionality.

What is the os module in the Python programming language?

It provides various functions to interact with the operating system. We can do tasks like creating, deleting, changing, renaming a directory, etc.

How can we use the os module in Python?

We can simply import the os module using "import os" in our code.

Is the os module inbuilt in Python?

Yes, the os module is inbuilt in Python. It is part of the standard library.

Which function allows you to see the current working directory?

The os.getcwd() function allows us to see the current working directory.

Which is the common type of exception which is thrown in the os module?

The OSError exception is the most common type of exception which is thrown when the functions in the os module are not properly used.

Conclusion

  • The os module provided in Python provides various functions through which we can do certain tasks that are done by the operating system. 
  • Tasks like creating a directory, deleting a directory, changing the directory, etc., can be done very easily.
  • In order to get the location of the current working directory in the system, we use the getcwd() function.
  • We can also change the current working directory using the os.chdir() function provided in the os module.
  • We can create a new directory using the os.mkdir() function and the os.makedirs() function of the os module. 
  • We can rename a file or a directory using the os.rename() function of the os module in Python.
  • We can perform various path-related tasks using the functions present in the os.path.
Live masterclass