Tutorial

Python os module

Published on August 3, 2022
Default avatar

By Shubham

Python os module

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Python OS module provides easy functions that allow us to interact and get Operating System information and even control processes up to a limit.

Python OS Module

The functions OS module provides allows us to operate on underlying Operating System tasks, irrespective of it being a Windows Platform, Macintosh or Linux. In this lesson, we will review these functions and what we can do with these. Let us start our journey with these functions and what information they offer.

Python import os

Please note that first of all we have to import OS module in our program, then only we can execute any of it’s functions. python os import, python os module

os.name

This function gives the name of the OS module it imports. This differs based on the underlying Operating System. Currently, it registers ‘posix’, ‘os2’, ‘ce’, ‘nt’, ‘riscos’ and ‘java’. Let’s execute this on the system:

>>> print(os.name)
posix

Clearly, this can output different platforms based on the interpreter.

os.environ

environ is not a function but a process parameter through which we can access environment variables of the system. Let’s see sample code snippet:

import os
output = os.environ['HOME']
print(output)

When we run this script, the following will be the output: python os environment variable We can use it to work with the environment variables, read more at Python set environment variable.

os.execvp

execvp function is one of the ways to run other commands on the system. Let’s see sample code snippet for this function:

import os
program = "python"
arguments = ["hello.py"]
print(os.execvp(program, (program,) +  tuple(arguments)))

For this, we just created a sample script as hello.py with following code:

print('Hello')

When we run this script, the following will be the output: python os module, python os execute other script

os.getuid

This os module function returns current process’s user ID or UID, as it is populary known.

>>> os.getuid()
501

So, the current shell process ID is 501.

os.rename

With the python os rename function, we can easily rename a file.

import os
fileDir = "JournalDev.txt"
os.rename(fd,'JournalDev_Hi.txt')

Note that for this, we must provide correct permissions to our script.

os.system

Python os system function allows us to run a command in the Python script, just like if I was running it in my shell. For example:

import os
currentFiles = os.system("users > users.txt")

When I ran this script, a new file was made in the same directory with name users.txt and content String as ‘shubham’ as this is returned by original shell as well: Python OS System command Note that this is a very powerful command and should be used cautiously.

os.error

Python os module error class is the base class for I/O related errors. So we can catch IO errors using OSError in the except clause.

import os

try:
    f = open('abc.txt', 'r')  # file is missing
except OSError:
    print('Error')

os.getpid

This function returns current process ID or PID, as it is populary known.

>>> os.getpid()
71622

So, the current shell process’s user ID is 71622.

os.listdir

This function just lists out the files and directories present in the current working directory.

>>> import os
>>> os.listdir()
['.DS_Store', '.localized', 'JournalDev', 'Java', 'Python']

It returns an iterable list of directory and file names.

os.uname

This function return information which identifies current Operating System on which this is executed.

>>> os.uname()
posix.uname_result(sysname='Darwin', nodename='Shubham.local', release='17.2.0', version='Darwin Kernel Version 17.2.0: Fri Sep 29 18:27:05 PDT 2017; root:xnu-4570.20.62~3/RELEASE_X86_64', machine='x86_64')

That was prettry detailed actually.

import os.path vs import os

os.path works strangely actually. It looks like os packaged with a submodule path but actually, os is a normal module which operate with sys.module to support os.path. Let us list what happens behind the scenes:

  • When Python starts, it loads many modules into sys.module.
  • os module is also loaded when Python starts. It assigns its path to the os specific module attribute.
  • It injects sys.modules['os.path'] = path so that you’re able to do import os.path as though it was a submodule.

Summary

In this lesson, we read about various functions provided by OS module in Python and saw how they work. See more lessons on Python here. Reference: API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Shubham

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 11, 2019

we need something more as the students as new to this compiler

- Vishwas Narayan

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more
    DigitalOcean Cloud Control Panel