DEV Community

importostar
importostar

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
    print(dir(os))

You can try it in the Python shell:

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

key functions of the os module

os.name

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: ',os.name)

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

os.getcwd()

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

    import os 
    print(os.getcwd())

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

os.chdir()

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()
'/home/you'
>>> os.chdir('/home/you/test')
>>> os.getcwd()
'/home/you/test'
>>> 

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

Links:

Top comments (0)