The Python Standard Library is a collection of modules and packages that come pre-installed with Python. It provides a wide range of functionality, allowing developers to perform various tasks without needing additional installations. This article explores some commonly used modules in the Python Standard Library with examples.
math
ModuleThe math
module provides mathematical functions such as trigonometry, logarithms, and constants like pi
.
import math # Calculate the square root of a number print("Square root of 25:", math.sqrt(25)) # Use the constant pi print("Value of pi:", math.pi) # Calculate the cosine of 0 print("Cosine of 0:", math.cos(0))
random
ModuleThe random
module is used to generate random numbers or make random choices.
import random # Generate a random integer between 1 and 10 print("Random integer:", random.randint(1, 10)) # Choose a random element from a list choices = ['apple', 'banana', 'cherry'] print("Random choice:", random.choice(choices)) # Shuffle a list numbers = [1, 2, 3, 4, 5] random.shuffle(numbers) print("Shuffled list:", numbers)
datetime
ModuleThe datetime
module helps in working with dates and times.
import datetime # Get the current date and time current_time = datetime.datetime.now() print("Current date and time:", current_time) # Create a specific date specific_date = datetime.date(2023, 11, 29) print("Specific date:", specific_date) # Calculate the difference between two dates date1 = datetime.date(2024, 1, 1) date2 = datetime.date(2023, 11, 29) difference = date1 - date2 print("Days until New Year:", difference.days)
os
ModuleThe os
module provides functions to interact with the operating system.
import os # Get the current working directory print("Current working directory:", os.getcwd()) # List files in the current directory print("Files in directory:", os.listdir()) # Create a new directory os.mkdir("example_directory") print("Directory created: example_directory")
zipfile
ModuleThe zipfile
module allows you to work with ZIP archives.
import zipfile # Create a ZIP file with zipfile.ZipFile("example.zip", "w") as zipf: zipf.write("example.txt") print("Created example.zip") # Extract a ZIP file with zipfile.ZipFile("example.zip", "r") as zipf: zipf.extractall("extracted_files") print("Extracted files to extracted_files")
urllib
ModuleThe urllib
module is used for fetching data from URLs.
import urllib.request # Fetch data from a URL url = "http://example.com" response = urllib.request.urlopen(url) html_content = response.read().decode("utf-8") print("HTML content of example.com:") print(html_content)
The Python Standard Library is an invaluable resource for developers, offering tools for a wide range of tasks. Whether you need to perform mathematical operations, manipulate dates, handle files, or access the internet, the standard library has you covered. Exploring and mastering these modules can significantly enhance your productivity in Python.