Python – OS Module

Created with Sketch.

Python – OS Module

It is possible to automatically perform many operating system tasks. The OS module in Python provides functions for creating and removing a directory (folder), fetching its contents, changing and identifying the current directory, etc.

Creating Directory

We can create a new directory using the mkdir() function from the OS module.


>>> import os
>>>os.mkdir(“d:\\tempdir”)

A new directory corresponding to the path in the string argument of the function will be created. If we open D drive in Windows Explorer, we should notice tempdir folder created.

Changing the Current Working Directory

We must first change the current working directory to a newly created one before doing any operations in it. This is done using the chdir() function.


>>> import os
>>>os.chdir(“d:\\tempdir”)

There is a getcwd() function in the OS module using which we can confirm if the current working directory has been changed or not.


>>>os.getcwd()
‘d:\\tempdir’

Directory paths can also be relative. If the current directory is set to D drive and then to tempdir without mentioning the preceding path, then also the current working directory will be changed to d:\tempdir.


>>>os.chdir(“d:\\”)
>>>os.getcwd()
‘d:\\’
>>>os.chdir(“tempdir”)
>>>os.getcwd()
‘d:\\tempdir’

In order to set the current directory to the parent directory use “..” as the argument in the chdir() function.


>>>os.chdir(“d:\\tempdir”)
>>>os.getcwd()
‘d:\\tempdir’
>>>os.chdir(“..”)
>>>os.getcwd()
‘d:\\’

Removing a Directory

The rmdir() function in the OS module removes the specified directory either with an absolute or relative path.
However, we can not remove the current working directory. Also, for a directory to be removed, it should be empty.
For example, tempdir will not be removed if it is the current directory. We have to change the current working directory and then remove tempdir.


>>>os.chdir(“tempdir”)
>>>os.getcwd()
‘d:\\tempdir’
>>>os.rmdir(“d:\\tempdir”)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: ‘d:\\tempdir’
>>>os.chdir(“..”)
>>>os.rmdir(“tempdir”)

List Files and Sub-directories

The listdir() function returns the list of all files and directories in the specified directory.


>>>os.listdir(“c:\python37”)
[‘DLLs’, ‘Doc’, ‘fantasy-1.py’, ‘fantasy.db’, ‘fantasy.py’, ‘frame.py’, ‘gridexample.py’, ‘include’, ‘Lib’, ‘libs’, ‘LICENSE.txt’, ‘listbox.py’, ‘NEWS.txt’, ‘place.py’, ‘players.db’, ‘python.exe’, ‘python3.dll’, ‘python36.dll’, ‘pythonw.exe’, ‘sclst.py’, ‘Scripts’, ‘tcl’, ‘test.py’, ‘Tools’, ‘tooltip.py’, ‘vcruntime140.dll’, ‘virat.jpg’, ‘virat.py’]

If we don’t specify any directory, then list of files and directories in the current working directory will be returned.


>>>os.listdir()
[‘.config’, ‘.dotnet’, ‘python’]

Learn more about OS modules in Python docs.

Leave a Reply

Your email address will not be published. Required fields are marked *