Python OS Module Tutorial

The Python OS module facilitates communication between the user and the operating system. It includes a variety of valuable OS functions that are utilized to execute operating system-related tasks and retrieve pertinent information regarding the operating system.

The OS module is part of Python's standard utility offerings. This module provides a consistent method for accessing functionality that varies with the operating system. It enables us to manage files and directories effectively.

In order to utilize the OS module, it is necessary to import the OS module first.

Example

import os

The OS module contains several functions, which are outlined below:

1. os.name

This function returns the name of the operating system module that it incorporates. At present, it registers the following: 'posix', 'nt', 'os2', 'ce', 'java', and 'riscos'.

Python os.name Module Example

Let's consider an illustration to showcase the functionality of the os.name module in Python.

Example

import os

print(os.name)

Output:

2. os.mkdir

The function os.mkdir is utilized for the purpose of establishing a new directory.

Python os.mkdir Module Example

Let us consider an example to illustrate the usage of the os.mkdir function in Python.

Example

import os

os.mkdir("d:\\newdir")

This will generate a new directory in the specified path provided as a string argument to the function, located on the D drive, and named folder newdir.

3. os.getcwd

It provides the present working directory (CWD) associated with the file.

Python os.getcwd Module Example

For illustrative purposes, let us consider an example to showcase the usage of the os.getcwd function in Python.

Example

import os

print(os.getcwd())

Output:

Output

C:\Users\Python\Desktop\ModuleOS

4. os.chdir

The os module includes the chdir function, which allows users to modify the current working directory.

Python os.chdir module Example

Let us examine an illustration to showcase the os.chdir function within Python.

Example

import os

os.chdir("d:\\")

Output:

5. os.rmdir

The rmdir function is utilized to delete a designated directory, which can be specified using either an absolute or a relative path. Initially, it is necessary to navigate to the current working directory before proceeding to eliminate the folder.

Python os.rmdir Module Example

To illustrate the functionality of the os.rmdir function in Python, let’s consider a practical example.

Example

import os

# It will throw a Permission error; that's why we have to change the current working directory.

os.rmdir("d:\\newdir")

os.chdir("..")

os.rmdir("newdir")

6. os.error

The os.error function identifies errors at the operating system level. It raises an OSError when there are issues such as invalid or unreachable file names and paths, among other related problems.

Python os.error module Example

Let’s consider an example to illustrate the functionality of the os.error module in Python.

Example

import os

try:

    # If file does not exist,

    # then it throw an IOError

    filename = 'Python.txt'

    f = open(filename, 'rU')

    text = f.read()

    f.close()

# The Control jumps directly to here if

# any lines throws IOError.

except IOError:

    # print(os.error) will <class 'OSError'>

    print('Problem reading: ' + filename)

Output:

Output

Problem reading: Python.txt

7. os.popen

This function initiates the opening of a file, or one that is indicated by the provided command, and it yields a file object that is linked to a pipe.

Python os.popen Module Example

Let's consider an example to illustrate the functionality of the os.popen module in Python.

Example

import os

fd = "python.txt"

# popen() is similar to open()

file = open(fd, 'w')

file.write("This is awesome")

file.close()

file = open(fd, 'r')

text = file.read()

print(text)

# popen() provides gateway and accesses the file directly

file = os.popen(fd, 'w')

file.write("This is awesome")

# File not closed, shown in next function.

Output:

Output

This is awesome

8. os.close

This function terminates the connection to the file linked with the descriptor fr.

Python os.close Module Example

Let us consider an example to illustrate the use of the os.close function in Python.

Example

import os

fr = "Python1.txt"

file = open(fr, 'r')

text = file.read()

print(text)

os.close(file)

Output:

Output

Traceback (most recent call last):

File "main.py", line 3, in

file = open(fr, 'r')

FileNotFoundError: [Errno 2] No such file or directory: 'Python1.txt'

9. os.rename

A file or directory can be modified in terms of its name by utilizing the function os.rename. A user is permitted to alter the name of the file provided they possess the necessary permissions to make changes to that file.

Python os.rename Module Example

To illustrate the functionality of the os.rename function in Python, we will consider an example.

Example

import os

fd = "python.txt"

os.rename(fd,'Python1.txt')

os.rename(fd,'Python1.txt')

Output:

Output

Traceback (most recent call last):

  File "main.py", line 3, in

    os.rename(fd,'Python1.txt')

FileNotFoundError: [Errno 2] No such file or directory: 'python.txt' -> 'Python1.txt'

10. os.access

This function leverages the actual user ID and group ID to verify whether the user who invoked it possesses the necessary permissions to access the specified path.

Python os.access Module Example

Let us consider an example to illustrate the functionality of the os.access method in Python.

Example

import os

import sys

path1 = os.access("Python.txt", os.F_OK)

print("Exist path:", path1)

# Checking access with os.R_OK

path2 = os.access("Python.txt", os.R_OK)

print("It access to read the file:", path2)

# Checking access with os.W_OK

path3 = os.access("Python.txt", os.W_OK)

print("It access to write the file:", path3)

# Checking access with os.X_OK

path4 = os.access("Python.txt", os.X_OK)

print("Check if path can be executed:", path4)

Output:

Output

Exist path: False

It access to read the file: False

It access to write the file: False

Check if path can be executed: False

Conclusion

In this tutorial, we explored the OS module available in Python. The OS module serves as a means to facilitate communication between the user and the operating system. To utilize the OS module, we can import it using the command import os. We examined several functions within the OS module, including os.name, os.mkdir, os.getcwd, os.close, among others, accompanied by examples to enhance our comprehension of the subject matter.

Python OS Module FAQs

1. What is the Python OS module?

The Python OS module enables users to interact efficiently with the operating system. It presents a variety of valuable functions designed for executing operating system-related tasks and retrieving pertinent information about the operating system.

2. How can we import the os module?

We can import the os module in Python by:

Example

import os

3. What are common uses of the os module?

  • The os module helps in File and directory operations with functions like os.mkdir, os.remove, and os.listdir.
  • It helps working with paths with functions like os.path.join, os.path.exists.
  • Os modules manage the environment variables.
  • It assists in running system commands with the os.system function.
  • It is also useful in getting system information (os.name, os.getcwd.
  • 4. How can we get the current working directory?

To obtain the current working directory, we can utilize the following code:

Example

import os

print(os.getcwd())

5. What is the difference between os.remove and os.rmdir?

The function os.remove is utilized to eliminate a file, while the function os.rmdir is specifically designed to remove an empty directory.

Input Required

This code uses input(). Please provide values below: