DEV Community


Posted on


os module in python with examples

This article is about the Python programming language, the os module (operating system) lets you grab some useful information.

The os module contains functions for interacting with the operating system. The os module can not be installed since it is an integrated Python module.

By using it, you can perform additional tasks such as identifying the operating system, navigating the file system and performing many other operations.

If you are new to Python, I recommend this course/book.

You can list all data in the os module with the dir() function.

    # load os module
    import os 

    # show directives

You can try it in the Python shell:

>>> import os
>>> print(dir(os))

key functions of the os module

This function gives the name of the OS you run in your own system. The output of this function will be unique from system
to system, as not the same operating system is used.

    import os 
    print( 'Name of OS: ',

This can output 'posix', 'nt' for windows nt etc.


This function is short for 'get current working directory' (cwd), it returns the programs current working directory.

    import os 

It output the current working directory like /home/you/ or C:\Users\you


This function is used to modify the path of the file used for code execution. It takes the new path as a parameter in the form of a string. Before you change the directory, use the mkdir() function to create a new directory.

>>> import os
>>> os.mkdir('/home/you/test')
>>> os.getcwd()
>>> os.chdir('/home/you/test')
>>> os.getcwd()

This creates a new directory, shows the current directory, changes the directory and then shows the current directory again. (used this script as reference)


Top comments (0)

Super Useful CSS Resources

A collection of 70 hand-picked, web-based tools which are actually useful.
Each will generate pure CSS without the need for JS or any external libraries.