Category: python
Python os Module
Published on 24 Jul 2026
Explanation
The os module provides a portable way to interact with the operating system. It allows Python programs to work with
Code:
import os
# Current working directory
print('Current Directory:', os.getcwd())
# List files and folders
print(os.listdir())
# Create a new directory
os.mkdir('DemoFolder')
print('Folder Created')
# Remove the directory
os.rmdir('DemoFolder')
print('Folder Removed')
Explanation
The sys module provides access to variables and functions related to the Python interpreter. It is commonly used to read
Code:
import sys
print('Python Version:')
print(sys.version)
print('\nPlatform Information:')
print(sys.platform)
print('\nCommand Line Arguments:')
print(sys.argv)
print('\nMaximum Integer Size:')
print(sys.maxsize)
Explanation
The math module provides mathematical functions such as square root, power, factorial, trigonometric functions, logarithms, and constants like pi. The
Code:
import math
import random
print('Square Root:', math.sqrt(81))
print('Power:', math.pow(2, 5))
print('Factorial:', math.factorial(5))
print('PI Value:', math.pi)
print('Random Integer:', random.randint(1, 100))
print('Random Float:', random.random())
colors = ['Red', 'Green', 'Blue', 'Yellow']
print('Random Choice:', random.choice(colors))
Explanation
The collections module provides specialized container data types that extend the functionality of Python's built-in data structures. Common classes include
Code:
from collections import Counter, defaultdict text = ['Python', 'Java', 'Python', 'React', 'Java', 'Python'] counter = Counter(text) print(counter) students = defaultdict(int) students['John'] += 1 students['Alice'] += 2 print(students) print(students['David'])
Explanation
Built-in modules are frequently combined in real-world applications to perform complex tasks efficiently. For example, an application may use the
Code:
import os
import math
import random
from collections import Counter
files = os.listdir('.')
print('Number of Files:', len(files))
numbers = [10, 20, 10, 30, 40, 20, 10]
print('Frequency:', Counter(numbers))
radius = random.randint(1, 10)
area = math.pi * radius ** 2
print('Random Radius:', radius)
print('Circle Area:', round(area, 2))