Home » Python OS module

Python OS module

This module provides a portable way of using operating system dependent functionality.

If you just want to read or write a file see open(), if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module.

For creating temporary files and directories see the tempfile module, and for high-level file and directory handling see the shutil module.

To work with the OS module, we need to import the OS module.

import os


There are several functions which can be performed using Python OS module, we go through some of them here


The name of the operating system is returned by the name() function.

Currently, it registers ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’ and ‘riscos’.

import os



The os.mkdir() function is used to create new directory. Consider the following example.

import os  

This creates a new directory to the path in the string argument of the function in the E drive named folder temp.

getcwd() function

The getcwd() method returns the path of the current working directory

import os



The chdir() function is used to change the current working directory. In this example we change to D

import os  


The remove() function deletes or removes a file from the system. We supply the name of the file and the path, and it will delete the file.

You do not need to specify the path when deleting a file from the current directory; however, we must specify the path when removing files or directories from other directories.

import os

print("file is removed!!")


The rename() function renames a file that already exists

It takes two arguments as parameters,the first argument is the old name and the second argument is the new name of file:

import os


rmdir() function

The rmdir() function is used to remove a directory from the operating system. It removes the directory and takes the file’s name and path as arguments.

There must be no files present in the directory.
The rmdir() function cannot be used to remove the current working directory.

import os


You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More