Python Libraries
✕os
- in-built library that provides functions for interacting with the operating system
- Use case: File and directory management, environment variables, etc.
| Function | Description | Example |
|---|---|---|
os.path.join() | Joins one or more path components intelligently. | os.path.join("folder", "subfolder", "file.txt") |
os.listdir() | Returns a list of the entries in the directory given by path. | os.listdir("folder") |
os.mkdir() | Creates a directory named path with numeric mode mode. | os.mkdir("new_folder") |
os.rename() | Renames the file or directory src to dst. | os.rename("old_name.txt", "new_name.txt") |
os.rmdir() | Removes a directory named path. | os.rmdir("folder") |
os.remove() | Removes (deletes) the file path. | os.remove("file.txt") |
os.path.getsize() | Returns the size of path in bytes. | os.path.getsize("file.txt") |
os.system() | Executes the command (a string) in a subshell. | os.system("ls -l") |
os.path.exists() | Returns True if path refers to an existing path. | os.path.exists("file.txt") |
Commonly Used Functions in OS Library
random
- in-built library that provides functions related to random operations
- Use case: Random number generation, shuffling data, etc.
| Function | Description | Example |
|---|---|---|
random.random() | Returns a random float number in the range [0.0, 1.0). | random.random() |
random.randint(a, b) | Returns a random integer N in range [a, b]. | random.randint(1, 10) |
random.choice(seq) | Returns a random element from the sequence seq. | random.choice([1, 2, 3, 4, 5]) |
random.shuffle(x) | Shuffles the sequence x in place. | my_list = [1, 2, 3, 4, 5]; random.shuffle(my_list) |
random.sample(seq, k) | Returns a k length list of unique elements from sequence. | random.sample([1, 2, 3, 4, 5], 3) |
random.seed(value) | Initializes the random number generator with a seed value. | random.seed(42) |
Commonly Used Functions in random Library
math
- in-built library that provides functions for mathematical operations
- Use case: Mathematical calculations, trigonometric functions, etc.
| Function | Description | Example |
|---|---|---|
math.floor(x) | Returns the largest integer less than or equal to x. | math.floor(3.7) |
math.ceil(x) | Returns the smallest integer greater than or equal to x. | math.ceil(3.2) |
math.sqrt(x) | Returns the square root of x. | math.sqrt(16) |
math.pow(x, y) | Returns x raised to the power of y. | math.pow(2, 3) |
math.sin(x) | Returns the sine of x radians. | math.sin(math.pi / 2) |
math.radians(x) | Converts angle x from degrees to radians. | math.radians(180) |
math.pi | Mathematical constant π (pi), approximately 3.14159. | math.pi |
math.log(x, base) | Returns the logarithm of x to the given base. | math.log(100, 10) |
math.factorial(n) | Returns the factorial of n. | math.factorial(5) |
math.gcd(a, b) | Returns the greatest common divisor of a and b. | math.gcd(12, 18) |
math.lcm(a, b) | Returns the least common multiple of a and b. | math.lcm(12, 18) |
Commonly Used Functions in math Library
mailerpy
- third-party library that provides functions for sending emails using Python.
- Installed as:
pip install mailerpy. - First, Generate secure gmail password. Then set it as environment variable
EMAIL_PASSWORD. from mailerpy import Mailer import os password = os.getenv("EMAIL_PASSWORD") mailer = Mailer("smtp.gmail.com", 587, "your_email", password) to_emails = ["[email protected]", "[email protected]"], subject = "Test Email from mailerpy" body = "Hello, this is a test email sent using mailerpy library in Python." attachment_list = [r'C:\Desktop\test.txt', 'test2.txt'] mailer.send_mail(to_emails, subject, body, attachments=attachment_list)
Example:
datetime
- in-built library that provides functions for manipulating dates and times.
- Use case: Date and time manipulation, formatting, etc.
- We often use
dateanddatetimesubmodule
| Function | Description | Example |
|---|---|---|
datetime.now() | Returns the current local date and time. | datetime.now() |
date.today() | Returns the current local date. | date.today() |
dt_obj.strftime(format) | Formats a datetime object into a string. | dt_obj.strftime("%Y-%m-%d") |
.strptime(string, format) | Parses a string into a datetime object. | datetime.strptime("2023-01-01", "%Y-%m-%d") |
dt_obj + timedelta(days=n) | Adds n days to a datetime object. | dt_obj + datetime.timedelta(days=7) |
d2 - d1 | Subtracts two dates, returning a timedelta. | d2 - d1 |
Commonly Used Functions in datetime Library
Common Datetime Formats
| Format | Description | Example |
|---|---|---|
%Y | Year | 2023 |
%m | Month | 01 |
%d | Day | 01 |
%H | Hour | 12 |
%M | Minute | 34 |
%S | Second | 56 |
%B | Full Month Name | January |
%b | Abbreviated Month Name | Jan |
%A | Full Weekday Name | Monday |
%a | Abbreviated Weekday Name | Mon |
%p | AM or PM | AM |
%j | Day of the Year | 001 |
%U | Week of the Year (Sunday as the First Day) | 01 |
%W | Week of the Year (Monday as the First Day) | 01 |
%w | Day of the Week | 0 (Sunday) |
%-d | Day of the Month (no leading zero) | 1 |
%-m | Month (no leading zero) | 1 |
%y | Year without century | 23 |
Common Datetime Formats and their Notation
requests
- third-party library that allows you to send HTTP requests easily.
- Installed as:
pip install requests. - Supports various HTTP methods like GET, POST, PUT, DELETE, etc.
import requests response = requests.get("https://www.google.com")print(response.status_code) # Output: 200 print(response.json()) # Output: JSON response from Google print(response.text) # Output: HTML content of the page print(response.headers) # Output: Response headers
Example:
beautifulsoup
- third-party library that allows you to parse HTML and XML documents.
- Installed as:
pip install beautifulsoup4. - Has methods like
find(),find_all(),select(), etc. to navigate and search the parse tree. from bs4 import BeautifulSoup import requests response = requests.get("https://www.google.com")soup = BeautifulSoup(response.text, "html.parser") print(soup.title.text)
Example:
pandas
- third-party library that provides data structures and data analysis tools.
- Installed as:
pip install pandas. import pandas as pd df = pd.read_csv(file_path) print(df.head()) print(df.describe()) filter_mask = (df["LTP"] > 150) & (df["LTP"] < 300) filtered_data = df[filter_mask] print(filtered_data.head()) filtered_data.to_csv("filtered_data.csv")
Example:
matplotlib
- third-party library that provides functions for creating static, animated, and interactive visualizations in Python.
- Installed as:
pip install matplotlib. import matplotlib.pyplot as plt# Creating a simple line plotx = [1, 2, 3, 4, 5] y = [10, 20, 25, 30, 40] plt.plot(x, y) plt.title("Line Plot") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.show()
Example:
