The Wayback Machine - https://web.archive.org/web/20240917121147/https://www.geeksforgeeks.org/os-module-python-examples/
Open In App

OS Module in Python with Examples

Last Updated : 01 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality.

The *os* and *os.path* modules include many functions to interact with the file system.

Python-OS-Module Functions

Here we will discuss some important functions of the Python os module :

  • Handling the Current Working Directory
  • Creating a Directory
  • Listing out Files and Directories with Python
  • Deleting Directory or Files using Python

Handling the Current Working Directory

Consider Current Working Directory(CWD) as a folder, where Python is operating. Whenever the files are called only by their name, Python assumes that it starts in the CWD which means that name-only reference will be successful only if the file is in the Python’s CWD.

Note: The folder where the Python script is running is known as the Current Directory. This is not the path where the Python script is located.

Getting the Current working directory

To get the location of the current working directory os.getcwd() is used.

Example: This code uses the os' module to get and print the current working directory (CWD) of the Python script. It retrieves the CWD using the os.getcwd()' and then prints it to the console.

Python
import os 
cwd = os.getcwd() 
print("Current working directory:", cwd) 

Output:

Current working directory: /home/nikhil/Desktop/gfg

Changing the Current working directory

To change the current working directory(CWD) os.chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.

Note: The current working directory is the folder in which the Python script is operating.

Example: The code checks and displays the current working directory (CWD) twice: before and after changing the directory up one level using os.chdir('../'). It provides a simple example of how to work with the current working directory in Python.

Python
import os 
def current_path(): 
    print("Current working directory before") 
    print(os.getcwd()) 
    print() 
current_path() 
os.chdir('../') 
current_path() 

Output:

Current working directory before
C:\Users\Nikhil Aggarwal\Desktop\gfg
Current working directory after
C:\Users\Nikhil Aggarwal\Desktop

Creating a Directory

There are different methods available in the OS module for creating a directory. These are –

  • os.mkdir()
  • os.makedirs()

Using os.mkdir()

By using os.mkdir() method in Python is used to create a directory named path with the specified numeric mode. This method raises FileExistsError if the directory to be created already exists.

Example:  This code creates two directories: “GeeksforGeeks” within the “D:/Pycharm projects/” directory and “Geeks” within the “D:/Pycharm projects” directory.

  • The first directory is created using the os.mkdir() method without specifying the mode.
  • The second directory is created using the same method, but a specific mode (0o666) is provided, which grants read and write permissions.
  • The code then prints messages to indicate that the directories have been created.
Python
import os
directory = "GeeksforGeeks"
parent_dir = "D:/Pycharm projects/"
path = os.path.join(parent_dir, directory)

os.mkdir(path)
print("Directory '% s' created" % directory)
directory = "Geeks"
parent_dir = "D:/Pycharm projects"
mode = 0o666
path = os.path.join(parent_dir, directory)
os.mkdir(path, mode)
print("Directory '% s' created" % directory)

Output:

Directory 'GeeksforGeeks' created
Directory 'Geeks' created

Using os.makedirs()

os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.

Example: This code creates two directories, “Nikhil” and “c”, within different parent directories. It uses the os.makedirs function to ensure that parent directories are created if they don’t exist.

It also sets the permissions for the “c” directory. The code prints messages to confirm the creation of these directories

Python
import os
directory = "Nikhil"
parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"
path = os.path.join(parent_dir, directory)
os.makedirs(path)
print("Directory '% s' created" % directory)
directory = "c"
parent_dir = "D:/Pycharm projects/GeeksforGeeks/a/b"
mode = 0o666
path = os.path.join(parent_dir, directory)
os.makedirs(path, mode)
print("Directory '% s' created" % directory)

Output:

Directory 'Nikhil' created
Directory 'c' created

Listing out Files and Directories with Python

There is os.listdir() method in Python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then the list of files and directories in the current working directory will be returned.

Example: This code lists all the files and directories in the root directory (“/”). It uses the os.listdir function to get the list of files and directories in the specified path and then prints the results.

Python
import os 
path = "/"
dir_list = os.listdir(path) 
print("Files and directories in '", path, "' :") 
print(dir_list) 

Output:

Files and directories in ' / ' :
['sys', 'run', 'tmp', 'boot', 'mnt', 'dev', 'proc', 'var', 'bin', 'lib64', 'usr',
'lib', 'srv', 'home', 'etc', 'opt', 'sbin', 'media']

Deleting Directory or Files using Python

OS module provides different methods for removing directories and files in Python. These are – 

  • Using os.remove()
  • Using os.rmdir()

Using os.remove() Method

os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.

Example: Suppose the file contained in the folder are:
 

Image

This code removes a file named “file1.txt” from the specified location “D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/”. It uses the os.remove function to delete the file at the specified path.

Python
import os 
file = 'file1.txt'
location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/"
path = os.path.join(location, file) 
os.remove(path) 

Output:

Image


Using os.rmdir()

os.rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.

Example: Suppose the directories are 

Image

This code attempts to remove a directory named “Geeks” located at “D:/Pycharm projects/”.

It uses the os.rmdir function to delete the directory. If the directory is empty, it will be removed. If it contains files or subdirectories, you may encounter an error.

Python
import os 
directory = "Geeks"
parent = "D:/Pycharm projects/"
path = os.path.join(parent, directory) 
os.rmdir(path) 

Output:

Image

Commonly Used Functions

Using os.name function

This function gives the name of the operating system dependent module imported. The following names have currently been registered: ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’ and ‘riscos’.

Python
import os
print(os.name)

Output:

posix

Note: It may give different output on different interpreters, such as ‘posix’ when you run the code here.

Using os.error Function

All functions in this module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. os.error is an alias for built-in OSError exception.

This code reads the contents of a file named ‘GFG.txt’. It uses a try…except block to handle potential errors, particularly the ‘IOError that may occur if there’s a problem reading the file.

If an error occurs, it will print a message saying, “Problem reading: GFG.txt.” 

Python
import os
try:
    filename = 'GFG.txt'
    f = open(filename, 'rU')
    text = f.read()
    f.close()
except IOError:
  print('Problem reading: ' + filename)

Output: 

Problem reading: GFG.txt

Using os.popen() Function

This method opens a pipe to or from command. The return value can be read or written depending on whether the mode is ‘r’ or ‘w’
Syntax: 

 os.popen(command[, mode[, bufsize]])

Parameters mode & bufsize are not necessary parameters, if not provided, default ‘r’ is taken for mode.

This code opens a file named ‘GFG.txt’ in write mode, writes “Hello” to it, and then reads and prints its contents. The use of os.popen is not recommended, and standard file operations are used for these tasks. 

Python
import os
fd = "GFG.txt"

file = open(fd, 'w')
file.write("Hello")
file.close()
file = open(fd, 'r')
text = file.read()
print(text)

file = os.popen(fd, 'w')
file.write("Hello")

Output: 

Hello

Note: Output for popen() will not be shown, there would be direct changes into the file.

Using os.close() Function

Close file descriptor fd. A file opened using open(), can be closed by close()only. But file opened through os.popen(), can be closed with close() or os.close(). If we try closing a file opened with open(), using os.close(), Python would throw TypeError. 

Python
import os
fd = "GFG.txt"
file = open(fd, 'r')
text = file.read()
print(text)
os.close(file)

Output: 

Traceback (most recent call last):
File "C:\Users\GFG\Desktop\GeeksForGeeksOSFile.py", line 6, in
os.close(file)
TypeError: an integer is required (got type _io.TextIOWrapper)

Note: The same error may not be thrown, due to the non-existent file or permission privilege.

Using os.rename() Function

A file old.txt can be renamed to new.txt, using the function os.rename(). The name of the file changes only if, the file exists and the user has sufficient privilege permission to change the file.

Python
import os
fd = "GFG.txt"
os.rename(fd,'New.txt')
os.rename(fd,'New.txt')

Output:

Traceback (most recent call last):
File "C:\Users\GFG\Desktop\ModuleOS\GeeksForGeeksOSFile.py", line 3, in
os.rename(fd,'New.txt')
FileNotFoundError: [WinError 2] The system cannot find the
file specified: 'GFG.txt' -> 'New.txt'

A file name “GFG.txt” exists, thus when os.rename() is used the first time, the file gets renamed.

Upon calling the function os.rename() second time, file “New.txt” exists and not “GFG.txt”  thus Python throws FileNotFoundError. 

Using os.remove() Function

Using the Os module we can remove a file in our system using the os.remove() method. To remove a file we need to pass the name of the file as a parameter. 

Python
import os #importing os module.
os.remove("file_name.txt") #removing the file.

The OS module provides us a layer of abstraction between us and the operating system.

When we are working with os module always specify the absolute path depending upon the operating system the code can run on any os but we need to change the path exactly. If you try to remove a file that does not exist you will get FileNotFoundError

Using os.path.exists() Function

This method will check whether a file exists or not by passing the name of the file as a parameter. OS module has a sub-module named PATH by using which we can perform many more functions. 

Python
import os 
#importing os module

result = os.path.exists("file_name") #giving the name of the file as a parameter.

print(result)

Output:

False

As in the above code, the file does not exist it will give output False. If the file exists it will give us output True. 

Using os.path.getsize() Function

In os.path.getsize() function, python will give us the size of the file in bytes. To use this method we need to pass the name of the file as a parameter.

Python
import os #importing os module
size = os.path.getsize("filename")
print("Size of the file is", size," bytes.")

Output:

Size of the file is 192 bytes.

OS Module in Python with Examples – FAQs

What is the OS module in Python?

The os module in Python provides a way to interact with the operating system. It includes functions to handle file operations, directory management, and other OS-related tasks.

import os

# Get current working directory
current_directory = os.getcwd()
print(current_directory)

# List files and directories in the current directory
files = os.listdir('.')
print(files)

What is an OS package?

An OS package generally refers to a collection of modules and tools designed to provide a standardized way of interacting with the operating system. In the context of Python, the os package/module provides functionality to interact with the operating system, allowing for file and directory manipulation, environment variable access, and process management.

What is OS name in Python?

os.name is an attribute of the os module that provides the name of the operating system-dependent module imported. This can help in identifying the platform the code is running on.

import os

# Get the OS name
os_name = os.name
print(os_name) # Output: 'posix', 'nt', 'java', etc.

What is the OS process in Python?

The OS process in Python refers to functions in the os module that allow interaction with system processes. This includes functions to create, terminate, and manage processes. For example, os.system() can be used to run shell commands.

import os

# Execute a system command
os.system('echo Hello, World!')

What is Python IO module?

The io module in Python provides the main facilities for dealing with various types of I/O (Input/Output). It is used to handle file reading and writing operations, among other I/O-related tasks. This module defines the base classes and functions for handling binary and text I/O.



Previous Article
Next Article

Similar Reads

colorsys module in Python with examples
The colorsys module in Python defines bidirectional conversions of color values between RGB (Red Green Blue) color and other three coordinate YIQ (Luminance (Y) In-phase Quadrature), HLS (Hue Lightness Saturation) and HSV (Hue Saturation Value). The colorsys module defines the following functions: colorsys.rgb_to_yiq(r, g, b): It convert the color
3 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | Writing to an excel file using openpyxl module
Prerequisite : Reading an excel file using openpyxl Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files. For example, user might have to go through thousands of rows and pick out few handful information to make small changes b
3 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
PyMsgBox module in Python
PyMsgBox is simple, cross-platform, purely implemented in Python for message boxes as JavaScript has. It uses Python's built-in Tkinter module for its GUI. Installation This module does not built-in Python. To install it type the below command in the terminal. pip install PyMsgBox There are four functions in PyMsgBox, which follow JavaScript’s mess
2 min read
uniform() method in Python Random module
uniform() is a method specified in the random library in Python 3. Nowadays, in general, day-day tasks, there's always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there's an inbuilt method, "uniform()" which performs this task with
2 min read
mode() function in Python statistics module
The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode.Python is very robust when it comes to
5 min read
median_low() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The low median is always a member of the data set. When the numb
4 min read
median_high() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The high median is always a member of the data set. When the num
4 min read
median_grouped() function in Python statistics module
Coming to Statistical functions, median of a data-set is the measure of robust central tendency, which is less affected by the presence of outliers in data. As seen previously, medians of an ungrouped data-set using median(), median_high(), median_low() functions. Python gives the option to calculate the median of grouped and continuous data functi
4 min read
stdev() method in Python statistics module
Statistics module in Python provides a function known as stdev() , which can be used to calculate the standard deviation. stdev() function only calculates standard deviation from a sample of data, rather than an entire population. To calculate standard deviation of an entire population, another function known as pstdev() is used. Standard Deviation
5 min read
Python | ASCII art using pyfiglet module
pyfiglet takes ASCII text and renders it in ASCII art fonts. figlet_format method convert ASCII text into ASCII art fonts. It takes following arguments : text font ( DEFAULT_FONT = 'standard' ) Command to install pyfiglet module : pip install pyfiglet Code #1: Text in default font # import pyfiglet module import pyfiglet result = pyfiglet.figlet_fo
6 min read
easyinput module in Python
easyinput module in Python offers an easy input interface analogous to cin stream in C++. It supports multiple data types including files and provides functionalities such as input till different data types, multi-line input, etc. Installation To install this module type the below command in the terminal. pip install easyinputFunction Usedread(*typ
3 min read
Python | Adjusting rows and columns of an excel file using openpyxl module
Prerequisites : Excel file using openpyxl writing | reading Set the height and width of the cells:Worksheet objects have row_dimensions and column_dimensions attributes that control row heights and column widths. A sheet’s row_dimensions and column_dimensions are dictionary-like values; row_dimensions contains RowDimension objects and column_dimens
3 min read
Python | Plotting charts in excel sheet using openpyxl module | Set - 1
Prerequisite: Reading & Writing to excel sheet using openpyxl Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Let's see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data poi
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set – 2
Prerequisite: Python | Plotting charts in excel sheet using openpyxl module | Set – 1 Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set 3
Prerequisite : Plotting charts in excel sheet using openpyxl module Set - 1 | Set – 2Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of r
7 min read
Python | Create and write on excel file using xlsxwriter module
XlsxWriter is a Python module for writing files in the XLSX file format. It can be used to write text, numbers, and formulas to multiple worksheets. Also, it supports features such as formatting, images, charts, page setup, auto filters, conditional formatting and many others.Use this command to install xlsxwriter module: pip install xlsxwriter Not
3 min read
spwd module in Python
spwd module in Python provides access to the Unix shadow password database. The entries stored in the database is tuple-like objects whose attributes are similar as the members of spwd structure defined in <shadow.h> header file. Following are the attributes of tuple-like object which represents the entries stored in Unix shadow password data
5 min read
Pygorithm module in Python
Pygorithm module is a Python module written purely in Python and for educational purposes only. One can get the code, time complexities and much more by just importing the required algorithm. It is a good way to start learning Python programming and understanding concepts. Pygorithm module can also help to learn the implementation of all major algo
2 min read
Python | Plotting Area charts in excel sheet using XlsxWriter module
Prerequisite: Create and write on an excel file XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data points. Series the
6 min read
Python | Getting started with SymPy module
SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python. SymPy only depends on mpmath, a pure Python library for arbitrary floating point arithmetic, making
4 min read
Python | Plotting bar charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel file.XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Bar charts using realtime data. Charts are composed of at least one series of one or more data points
6 min read
Python | Plotting Radar charts in excel sheet using XlsxWriter module
Prerequisite:Create and Write on excel file XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Radar charts using realtime data. Charts are composed of at least one series of one or more data points.
6 min read
Python | Plotting scatter charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel file. XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Scatter charts using realtime data. Charts are composed of at least one series of one or more data p
10 min read
Python | Plotting column charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel file.XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Column charts using realtime data. Charts are composed of at least one series of one or more data poi
7 min read
Python calendar module | itermonthdays2() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. itermonthdays2() method is used to get an iterator for the month in the year s
2 min read
Python calendar module : iterweekdays() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. iterweekdays() method returns an iterator for the week day numbers that will b
1 min read
Practice Tags :