Overview of commonly used modules in Python, including os, sys, math, and datetime.

1. os Module:

The os module provides a way of using operating system-dependent functionality, such as reading or writing to the file system, interacting with the environment, and executing system commands.

Common Functions:

  • os.getcwd(): Returns the current working directory.
import os

current_directory = os.getcwd()
  • os.listdir(path): Returns a list of entries in the given path.
files_in_directory = os.listdir('.')
  • os.path.join(path, *paths): Join one or more path components intelligently.
path = os.path.join('folder', 'subfolder', 'file.txt')

2. sys Module:

The sys module provides access to some variables used or maintained by the Python interpreter and functions that interact with the interpreter.

Common Functions:

  • sys.argv: List of command-line arguments passed to a Python script.
import sys

script_name = sys.argv[0]
arguments = sys.argv[1:]
print(f"Script Name: {script_name}\nArguments: {arguments}")
  • sys.exit([arg]): Exit from Python, raising a SystemExit exception with an optional exit message.
import sys

sys.exit("Exiting the program")

3. math Module:

The math module provides mathematical functions and constants.

Common Functions:

  • math.sqrt(x): Returns the square root of x.
import math

result = math.sqrt(25)
  • math.sin(x), math.cos(x), math.tan(x): Trigonometric functions.
angle = math.radians(30)
sin_value = math.sin(angle)
cos_value = math.cos(angle)
tan_value = math.tan(angle)

print(sin_value, cos_value, tan_value)

4. datetime Module:

The datetime module supplies classes for working with dates and times.

Common Classes and Functions:

  • datetime.datetime: Class representing both date and time.
from datetime import datetime

current_time = datetime.now()
  • datetime.timedelta: Class representing the difference between two dates or times.
from datetime import datetime, timedelta

today = datetime.now()
tomorrow = today + timedelta(days=1)

These are just a few examples of commonly used modules in Python. Exploring the documentation for each module can provide a deeper understanding of the available functions and classes, enabling you to leverage the full power of Python’s standard library in your projects.