[go: up one dir, main page]

0% found this document useful (0 votes)
4 views27 pages

Modules

The document provides a comprehensive overview of various built-in Python modules and their commonly used functions, including examples for each module. Key modules covered include math, os, sys, datetime, random, json, re, collections, itertools, functools, and others, detailing their functionalities and usage. This serves as a useful reference for Python developers to utilize standard library features effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views27 pages

Modules

The document provides a comprehensive overview of various built-in Python modules and their commonly used functions, including examples for each module. Key modules covered include math, os, sys, datetime, random, json, re, collections, itertools, functools, and others, detailing their functionalities and usage. This serves as a useful reference for Python developers to utilize standard library features effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Here’s a breakdown of the built-in functions provided by some of the commonly used Python

modules with examples:

1. math module:

Functions for mathematical operations.

math.sqrt(x): RHere’s a breakdown of the built-in functions provided by some of the


commonly used Python modules with examples:

1. math module:

Functions for mathematical operations.

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


• math.factorial(x): Returns the factorial of x.
• math.pow(x, y): Returns x raised to the power y.
• math.pi: Returns the value of π (pi).

python
Copy code
import math
print(math.sqrt(16)) # Output: 4.0
print(math.factorial(5)) # Output: 120
print(math.pow(2, 3)) # Output: 8.0
print(math.pi) # Output: 3.141592653589793

2. os module:

Functions to interact with the operating system.

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


• os.listdir(path): Returns a list of directory contents at the given path.
• os.mkdir(path): Creates a new directory at the specified path.
• os.remove(file): Removes a file at the given file path.

python
Copy code
import os
print(os.getcwd()) # Output: Current directory path
os.mkdir('test_dir') # Creates a directory named 'test_dir'
print(os.listdir()) # Output: ['test_dir', 'some_file.txt']
os.remove('some_file.txt') # Removes 'some_file.txt'

3. sys module:

Functions to interact with the Python interpreter.

• sys.exit(): Exits the Python interpreter.


• sys.version: Returns the Python version being used.
• sys.argv: List of command-line arguments passed to a Python script.
• sys.path: A list of directories that Python searches for modules.
python
Copy code
import sys
print(sys.version) # Output: Python version
print(sys.argv) # Output: Command-line arguments list
sys.exit() # Exits the interpreter

4. datetime module:

Functions for working with dates and times.

• datetime.now(): Returns the current date and time.


• datetime.strptime(date_string, format): Converts a string to a datetime
object.
• datetime.timedelta(days=x): Returns a date that is x days ahead/behind the
current date.
• datetime.date.today(): Returns the current date.

python
Copy code
from datetime import datetime, timedelta
now = datetime.now()
print(now) # Output: Current date and time
print(now.strftime('%Y-%m-%d')) # Output: Date in the format YYYY-MM-DD
future_date = now + timedelta(days=5)
print(future_date) # Output: Current date + 5 days

5. random module:

Functions for generating random numbers.

• random.randint(a, b): Returns a random integer between a and b.


• random.random(): Returns a random float between 0 and 1.
• random.choice(seq): Returns a random element from the non-empty sequence seq.
• random.shuffle(list): Shuffles the sequence list in place.

python
Copy code
import random
print(random.randint(1, 10)) # Output: Random integer between 1 and 10
print(random.random()) # Output: Random float between 0 and 1
print(random.choice(['apple', 'banana', 'cherry'])) # Randomly picks an
item
list_ = [1, 2, 3, 4]
random.shuffle(list_)
print(list_) # Output: Shuffled list

6. json module:

Functions for working with JSON data.

• json.dumps(obj): Converts a Python object to a JSON string.


• json.loads(json_str): Parses a JSON string and returns a Python object.
• json.dump(obj, file): Writes JSON representation of a Python object to a file.
• json.load(file): Reads a JSON file and returns a Python object.

python
Copy code
import json
data = {"name": "John", "age": 30}
json_str = json.dumps(data) # Convert to JSON string
print(json_str) # Output: '{"name": "John", "age": 30}'
python_obj = json.loads(json_str)
print(python_obj['name']) # Output: John

7. re module:

Functions for working with regular expressions.

• re.match(pattern, string): Checks if the pattern matches the start of the string.
• re.search(pattern, string): Searches for the first occurrence of the pattern in the
string.
• re.findall(pattern, string): Returns a list of all matches of the pattern in the
string.
• re.sub(pattern, repl, string): Replaces occurrences of the pattern with repl.

python
Copy code
import re
pattern = r'\d+'
text = 'There are 123 apples'
match = re.findall(pattern, text) # Finds all digits
print(match) # Output: ['123']
text = re.sub(r'apples', 'bananas', text)
print(text) # Output: 'There are 123 bananas'

8. collections module:

Specialized data structures like namedtuple, deque, Counter.

• collections.Counter(list): Counts occurrences of elements in a list.


• collections.namedtuple(): Factory function for creating tuple subclasses.
• collections.defaultdict(): Dictionary with a default value for missing keys.
• collections.OrderedDict(): Dictionary that remembers the insertion order of
keys.

python
Copy code
from collections import Counter, defaultdict, namedtuple
# Counter
counts = Counter(['a', 'b', 'a', 'c', 'b', 'b'])
print(counts) # Output: Counter({'b': 3, 'a': 2, 'c': 1})

# Defaultdict
d = defaultdict(int)
d['apple'] += 1
print(d['apple']) # Output: 1
# Namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) # Output: 10 20

9. itertools module:

Functions for creating iterators for efficient looping.

• itertools.permutations(iterable): Returns all permutations of the iterable.


• itertools.combinations(iterable, r): Returns all combinations of length r.
• itertools.cycle(iterable): Repeats the elements of the iterable indefinitely.
• itertools.chain(*iterables): Combines multiple iterables into a single
sequence.

python
Copy code
import itertools
perms = itertools.permutations([1, 2, 3])
print(list(perms)) # Output: All permutations of [1, 2, 3]

combs = itertools.combinations([1, 2, 3], 2)


print(list(combs)) # Output: All combinations of length 2

10. functools module:

Higher-order functions for working with other functions.

• functools.reduce(function, iterable): Applies a function cumulatively to the


items of an iterable.
• functools.lru_cache(): Memoization decorator for functions, caching results.
• functools.partial(func, *args): Creates a partial function, fixing some
arguments.

python
Copy code
from functools import reduce
result = reduce(lambda x, y: x + y, [1, 2, 3, 4]) # Sums all elements
print(result) # Output: 10

These examples show how you can use the built-in functions of various standard Python
modules effectively.

4o

You said:

some more
ChatGPT said:

ChatGPT
Here are some additional built-in Python modules along with their commonly used functions
and examples:

11. time module:

Functions for working with time-related tasks.

• time.time(): Returns the current time in seconds since the epoch (1970-01-01).
• time.sleep(seconds): Pauses execution for the given number of seconds.
• time.ctime(): Converts a time expressed in seconds to a readable string format.
• time.strftime(format): Returns a string representing the date and time in a
specific format.

python
Copy code
import time
print(time.time()) # Output: Current time in seconds since the
epoch
time.sleep(2) # Pauses execution for 2 seconds
print(time.ctime()) # Output: Current date and time in a readable
format
print(time.strftime('%Y-%m-%d %H:%M:%S')) # Output: Custom formatted date-
time

12. calendar module:

Provides functions related to dates and calendars.

• calendar.month(year, month): Returns a string of the month’s calendar.


• calendar.isleap(year): Returns True if the year is a leap year.
• calendar.weekday(year, month, day): Returns the weekday of the given date.
• calendar.calendar(year): Returns a string with the calendar for the entire year.

python
Copy code
import calendar
print(calendar.month(2024, 9)) # Output: September 2024 calendar
print(calendar.isleap(2024)) # Output: True (2024 is a leap year)
print(calendar.weekday(2024, 9, 24)) # Output: Day of the week (0=Monday,
6=Sunday)
print(calendar.calendar(2024)) # Output: Full calendar of 2024

13. subprocess module:

Functions for creating and managing subprocesses.

• subprocess.run(args): Runs a command described by args.


• subprocess.Popen(): Executes a child program in a new process.
• subprocess.call(args): Runs a command described by args and waits for it to
complete.

python
Copy code
import subprocess
subprocess.run(['echo', 'Hello, World!']) # Output: Hello, World!

14. hashlib module:

Provides secure hash functions such as SHA-1, SHA-256, and MD5.

• hashlib.md5(): Creates an MD5 hash object.


• hashlib.sha256(): Creates a SHA-256 hash object.
• hashlib.sha1(): Creates a SHA-1 hash object.

python
Copy code
import hashlib
hash_object = hashlib.md5(b'Hello')
print(hash_object.hexdigest()) # Output: MD5 hash of the string 'Hello'

hash_object = hashlib.sha256(b'Hello')
print(hash_object.hexdigest()) # Output: SHA-256 hash of the string
'Hello'

15. configparser module:

Functions for handling configuration files.

• configparser.ConfigParser(): Creates a configuration file parser object.


• config.read(file): Reads a configuration file.
• config.get(section, option): Returns the value of a given option in a section.

python
Copy code
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
print(config.get('Settings', 'theme')) # Output: The value of the 'theme'
in 'Settings' section

16. csv module:

Functions to work with CSV (Comma-Separated Values) files.

• csv.reader(file): Reads data from a CSV file.


• csv.writer(file): Writes data to a CSV file.
• csv.DictReader(file): Reads CSV data as dictionaries.
• csv.DictWriter(file, fieldnames): Writes dictionaries to a CSV file.

python
Copy code
import csv
# Reading from a CSV file
with open('data.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row) # Output: Each row as a list
# Writing to a CSV file
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', '30', 'New York'])

17. logging module:

Provides a flexible framework for emitting log messages from Python programs.

• logging.basicConfig(): Configures the logging system.


• logging.debug(): Logs a message with level DEBUG.
• logging.info(): Logs a message with level INFO.
• logging.error(): Logs a message with level ERROR.

python
Copy code
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.error('This is an error message')

18. shutil module:

Provides high-level file operations like copying and removing files.

• shutil.copy(src, dst): Copies a file from src to dst.


• shutil.move(src, dst): Moves a file or directory to dst.
• shutil.rmtree(path): Deletes a directory and its contents.
• shutil.disk_usage(path): Returns disk usage statistics.

python
Copy code
import shutil
shutil.copy('source.txt', 'destination.txt') # Copy file
shutil.move('source.txt', 'new_location.txt') # Move file
shutil.rmtree('test_dir') # Delete directory

19. zipfile module:

Functions for working with ZIP archives.

• zipfile.ZipFile(file, mode): Creates or reads from a ZIP file.


• zipfile.ZipFile.write(filename): Adds a file to the ZIP archive.
• zipfile.ZipFile.extractall(path): Extracts all files from a ZIP archive.

python
Copy code
import zipfile
# Create a ZIP file
with zipfile.ZipFile('my_files.zip', 'w') as z:
z.write('file1.txt')
z.write('file2.txt')

# Extract from a ZIP file


with zipfile.ZipFile('my_files.zip', 'r') as z:
z.extractall('extracted')

20. glob module:

Provides a function for finding file paths matching a specified pattern.

• glob.glob(pattern): Returns a list of paths that match the specified pattern.

python
Copy code
import glob
print(glob.glob('*.txt')) # Output: List of all text files in the current
directory

21. uuid module:

Provides immutable UUID objects (universally unique identifiers).

• uuid.uuid4(): Generates a random UUID.


• uuid.uuid1(): Generates a UUID based on the host ID and current time.

python
Copy code
import uuid
unique_id = uuid.uuid4()
print(unique_id) # Output: A random UUID like 123e4567-e89b-12d3-a456-
426614174000

22. enum module:

Provides support for enumerations, which are a set of symbolic names bound to unique,
constant values.

• enum.Enum: Base class for creating enumerations.


• enum.auto(): Automatically assign values to enumeration members.

python
Copy code
from enum import Enum, auto
class Color(Enum):
RED = auto()
GREEN = auto()
BLUE = auto()

print(Color.RED) # Output: Color.RED

23. socket module:

Provides low-level networking interface for socket programming.


• socket.socket(): Creates a new socket.
• socket.bind(address): Binds the socket to an address.
• socket.listen(): Enables the server to accept connections.
• socket.connect(address): Connects the socket to the remote address.

python
Copy code
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 8080)) # Bind to localhost on port 8080
s.listen(1) # Listen for incoming connections

These additional modules expand the functionality of Python and make it highly versatile for
tasks such as file handling, networking, logging, and much more.

• eturns the square root of x.

• math.factorial(x): Returns the factorial of x.

• math.pow(x, y): Returns x raised to the power y.

• math.pi: Returns the value of π (pi).

python

Copy code

import math

print(math.sqrt(16)) # Output: 4.0

print(math.factorial(5)) # Output: 120

print(math.pow(2, 3)) # Output: 8.0

print(math.pi) # Output: 3.141592653589793

2. os module:

Functions to interact with the operating system.

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

• os.listdir(path): Returns a list of directory contents at the given path.

• os.mkdir(path): Creates a new directory at the specified path.

• os.remove(file): Removes a file at the given file path.

python

Copy code

import os

print(os.getcwd()) # Output: Current directory path

os.mkdir('test_dir') # Creates a directory named 'test_dir'


print(os.listdir()) # Output: ['test_dir', 'some_file.txt']

os.remove('some_file.txt') # Removes 'some_file.txt'

3. sys module:

Functions to interact with the Python interpreter.

• sys.exit(): Exits the Python interpreter.

• sys.version: Returns the Python version being used.

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

• sys.path: A list of directories that Python searches for modules.

python

Copy code

import sys

print(sys.version) # Output: Python version

print(sys.argv) # Output: Command-line arguments list

sys.exit() # Exits the interpreter

4. datetime module:

Functions for working with dates and times.

• datetime.now(): Returns the current date and time.

• datetime.strptime(date_string, format): Converts a string to a datetime object.

• datetime.timedelta(days=x): Returns a date that is x days ahead/behind the current date.

• datetime.date.today(): Returns the current date.

python

Copy code

from datetime import datetime, timedelta

now = datetime.now()

print(now) # Output: Current date and time

print(now.strftime('%Y-%m-%d')) # Output: Date in the format YYYY-MM-DD

future_date = now + timedelta(days=5)

print(future_date) # Output: Current date + 5 days

5. random module:

Functions for generating random numbers.

• random.randint(a, b): Returns a random integer between a and b.


• random.random(): Returns a random float between 0 and 1.

• random.choice(seq): Returns a random element from the non-empty sequence seq.

• random.shuffle(list): Shuffles the sequence list in place.

python

Copy code

import random

print(random.randint(1, 10)) # Output: Random integer between 1 and 10

print(random.random()) # Output: Random float between 0 and 1

print(random.choice(['apple', 'banana', 'cherry'])) # Randomly picks an item

list_ = [1, 2, 3, 4]

random.shuffle(list_)

print(list_) # Output: Shuffled list

6. json module:

Functions for working with JSON data.

• json.dumps(obj): Converts a Python object to a JSON string.

• json.loads(json_str): Parses a JSON string and returns a Python object.

• json.dump(obj, file): Writes JSON representation of a Python object to a file.

• json.load(file): Reads a JSON file and returns a Python object.

python

Copy code

import json

data = {"name": "John", "age": 30}

json_str = json.dumps(data) # Convert to JSON string

print(json_str) # Output: '{"name": "John", "age": 30}'

python_obj = json.loads(json_str)

print(python_obj['name']) # Output: John

7. re module:

Functions for working with regular expressions.

• re.match(pattern, string): Checks if the pattern matches the start of the string.

• re.search(pattern, string): Searches for the first occurrence of the pattern in the string.

• re.findall(pattern, string): Returns a list of all matches of the pattern in the string.
• re.sub(pattern, repl, string): Replaces occurrences of the pattern with repl.

python

Copy code

import re

pattern = r'\d+'

text = 'There are 123 apples'

match = re.findall(pattern, text) # Finds all digits

print(match) # Output: ['123']

text = re.sub(r'apples', 'bananas', text)

print(text) # Output: 'There are 123 bananas'

8. collections module:

Specialized data structures like namedtuple, deque, Counter.

• collections.Counter(list): Counts occurrences of elements in a list.

• collections.namedtuple(): Factory function for creating tuple subclasses.

• collections.defaultdict(): Dictionary with a default value for missing keys.

• collections.OrderedDict(): Dictionary that remembers the insertion order of keys.

python

Copy code

from collections import Counter, defaultdict, namedtuple

# Counter

counts = Counter(['a', 'b', 'a', 'c', 'b', 'b'])

print(counts) # Output: Counter({'b': 3, 'a': 2, 'c': 1})

# Defaultdict

d = defaultdict(int)

d['apple'] += 1

print(d['apple']) # Output: 1

# Namedtuple

Point = namedtuple('Point', ['x', 'y'])

p = Point(10, 20)
print(p.x, p.y) # Output: 10 20

9. itertools module:

Functions for creating iterators for efficient looping.

• itertools.permutations(iterable): Returns all permutations of the iterable.

• itertools.combinations(iterable, r): Returns all combinations of length r.

• itertools.cycle(iterable): Repeats the elements of the iterable indefinitely.

• itertools.chain(*iterables): Combines multiple iterables into a single sequence.

python

Copy code

import itertools

perms = itertools.permutations([1, 2, 3])

print(list(perms)) # Output: All permutations of [1, 2, 3]

combs = itertools.combinations([1, 2, 3], 2)

print(list(combs)) # Output: All combinations of length 2

10. functools module:

Higher-order functions for working with other functions.

• functools.reduce(function, iterable): Applies a function cumulatively to the items of an


iterable.

• functools.lru_cache(): Memoization decorator for functions, caching results.

• functools.partial(func, *args): Creates a partial function, fixing some arguments.

python

Copy code

from functools import reduce

result = reduce(lambda x, y: x + y, [1, 2, 3, 4]) # Sums all elements

print(result) # Output: 10

These examples show how you can use the built-in functions of various standard Python modules
effectively.

Here’s a breakdown of the built-in functions provided by some of the commonly used
Python modules with examples:

1. math module:
Functions for mathematical operations.

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


• math.factorial(x): Returns the factorial of x.
• math.pow(x, y): Returns x raised to the power y.
• math.pi: Returns the value of π (pi).

python
Copy code
import math
print(math.sqrt(16)) # Output: 4.0
print(math.factorial(5)) # Output: 120
print(math.pow(2, 3)) # Output: 8.0
print(math.pi) # Output: 3.141592653589793

2. os module:

Functions to interact with the operating system.

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


• os.listdir(path): Returns a list of directory contents at the given path.
• os.mkdir(path): Creates a new directory at the specified path.
• os.remove(file): Removes a file at the given file path.

python
Copy code
import os
print(os.getcwd()) # Output: Current directory path
os.mkdir('test_dir') # Creates a directory named 'test_dir'
print(os.listdir()) # Output: ['test_dir', 'some_file.txt']
os.remove('some_file.txt') # Removes 'some_file.txt'

3. sys module:

Functions to interact with the Python interpreter.

• sys.exit(): Exits the Python interpreter.


• sys.version: Returns the Python version being used.
• sys.argv: List of command-line arguments passed to a Python script.
• sys.path: A list of directories that Python searches for modules.

python
Copy code
import sys
print(sys.version) # Output: Python version
print(sys.argv) # Output: Command-line arguments list
sys.exit() # Exits the interpreter

4. datetime module:

Functions for working with dates and times.

• datetime.now(): Returns the current date and time.


• datetime.strptime(date_string, format): Converts a string to a datetime
object.
• datetime.timedelta(days=x): Returns a date that is x days ahead/behind the
current date.
• datetime.date.today(): Returns the current date.

python
Copy code
from datetime import datetime, timedelta
now = datetime.now()
print(now) # Output: Current date and time
print(now.strftime('%Y-%m-%d')) # Output: Date in the format YYYY-MM-DD
future_date = now + timedelta(days=5)
print(future_date) # Output: Current date + 5 days

5. random module:

Functions for generating random numbers.

• random.randint(a, b): Returns a random integer between a and b.


• random.random(): Returns a random float between 0 and 1.
• random.choice(seq): Returns a random element from the non-empty sequence seq.
• random.shuffle(list): Shuffles the sequence list in place.

python
Copy code
import random
print(random.randint(1, 10)) # Output: Random integer between 1 and 10
print(random.random()) # Output: Random float between 0 and 1
print(random.choice(['apple', 'banana', 'cherry'])) # Randomly picks an
item
list_ = [1, 2, 3, 4]
random.shuffle(list_)
print(list_) # Output: Shuffled list

6. json module:

Functions for working with JSON data.

• json.dumps(obj): Converts a Python object to a JSON string.


• json.loads(json_str): Parses a JSON string and returns a Python object.
• json.dump(obj, file): Writes JSON representation of a Python object to a file.
• json.load(file): Reads a JSON file and returns a Python object.

python
Copy code
import json
data = {"name": "John", "age": 30}
json_str = json.dumps(data) # Convert to JSON string
print(json_str) # Output: '{"name": "John", "age": 30}'
python_obj = json.loads(json_str)
print(python_obj['name']) # Output: John

7. re module:
Functions for working with regular expressions.

• re.match(pattern, string): Checks if the pattern matches the start of the string.
• re.search(pattern, string): Searches for the first occurrence of the pattern in the
string.
• re.findall(pattern, string): Returns a list of all matches of the pattern in the
string.
• re.sub(pattern, repl, string): Replaces occurrences of the pattern with repl.

python
Copy code
import re
pattern = r'\d+'
text = 'There are 123 apples'
match = re.findall(pattern, text) # Finds all digits
print(match) # Output: ['123']
text = re.sub(r'apples', 'bananas', text)
print(text) # Output: 'There are 123 bananas'

8. collections module:

Specialized data structures like namedtuple, deque, Counter.

• collections.Counter(list): Counts occurrences of elements in a list.


• collections.namedtuple(): Factory function for creating tuple subclasses.
• collections.defaultdict(): Dictionary with a default value for missing keys.
• collections.OrderedDict(): Dictionary that remembers the insertion order of
keys.

python
Copy code
from collections import Counter, defaultdict, namedtuple
# Counter
counts = Counter(['a', 'b', 'a', 'c', 'b', 'b'])
print(counts) # Output: Counter({'b': 3, 'a': 2, 'c': 1})

# Defaultdict
d = defaultdict(int)
d['apple'] += 1
print(d['apple']) # Output: 1

# Namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) # Output: 10 20

9. itertools module:

Functions for creating iterators for efficient looping.

• itertools.permutations(iterable): Returns all permutations of the iterable.


• itertools.combinations(iterable, r): Returns all combinations of length r.
• itertools.cycle(iterable): Repeats the elements of the iterable indefinitely.
• itertools.chain(*iterables): Combines multiple iterables into a single
sequence.

python
Copy code
import itertools
perms = itertools.permutations([1, 2, 3])
print(list(perms)) # Output: All permutations of [1, 2, 3]

combs = itertools.combinations([1, 2, 3], 2)


print(list(combs)) # Output: All combinations of length 2

10. functools module:

Higher-order functions for working with other functions.

• functools.reduce(function, iterable): Applies a function cumulatively to the


items of an iterable.
• functools.lru_cache(): Memoization decorator for functions, caching results.
• functools.partial(func, *args): Creates a partial function, fixing some
arguments.

python
Copy code
from functools import reduce
result = reduce(lambda x, y: x + y, [1, 2, 3, 4]) # Sums all elements
print(result) # Output: 10

These examples show how you can use the built-in functions of various standard Python
modules effectively.

4o

You said:

some more
ChatGPT said:

ChatGPT

Here are some additional built-in Python modules along with their commonly used functions
and examples:

11. time module:

Functions for working with time-related tasks.

• time.time(): Returns the current time in seconds since the epoch (1970-01-01).
• time.sleep(seconds): Pauses execution for the given number of seconds.
• time.ctime(): Converts a time expressed in seconds to a readable string format.
• time.strftime(format): Returns a string representing the date and time in a
specific format.

python
Copy code
import time
print(time.time()) # Output: Current time in seconds since the
epoch
time.sleep(2) # Pauses execution for 2 seconds
print(time.ctime()) # Output: Current date and time in a readable
format
print(time.strftime('%Y-%m-%d %H:%M:%S')) # Output: Custom formatted date-
time

12. calendar module:

Provides functions related to dates and calendars.

• calendar.month(year, month): Returns a string of the month’s calendar.


• calendar.isleap(year): Returns True if the year is a leap year.
• calendar.weekday(year, month, day): Returns the weekday of the given date.
• calendar.calendar(year): Returns a string with the calendar for the entire year.

python
Copy code
import calendar
print(calendar.month(2024, 9)) # Output: September 2024 calendar
print(calendar.isleap(2024)) # Output: True (2024 is a leap year)
print(calendar.weekday(2024, 9, 24)) # Output: Day of the week (0=Monday,
6=Sunday)
print(calendar.calendar(2024)) # Output: Full calendar of 2024

13. subprocess module:

Functions for creating and managing subprocesses.

• subprocess.run(args): Runs a command described by args.


• subprocess.Popen(): Executes a child program in a new process.
• subprocess.call(args): Runs a command described by args and waits for it to
complete.

python
Copy code
import subprocess
subprocess.run(['echo', 'Hello, World!']) # Output: Hello, World!

14. hashlib module:

Provides secure hash functions such as SHA-1, SHA-256, and MD5.

• hashlib.md5(): Creates an MD5 hash object.


• hashlib.sha256(): Creates a SHA-256 hash object.
• hashlib.sha1(): Creates a SHA-1 hash object.
python
Copy code
import hashlib
hash_object = hashlib.md5(b'Hello')
print(hash_object.hexdigest()) # Output: MD5 hash of the string 'Hello'

hash_object = hashlib.sha256(b'Hello')
print(hash_object.hexdigest()) # Output: SHA-256 hash of the string
'Hello'

15. configparser module:

Functions for handling configuration files.

• configparser.ConfigParser(): Creates a configuration file parser object.


• config.read(file): Reads a configuration file.
• config.get(section, option): Returns the value of a given option in a section.

python
Copy code
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
print(config.get('Settings', 'theme')) # Output: The value of the 'theme'
in 'Settings' section

16. csv module:

Functions to work with CSV (Comma-Separated Values) files.

• csv.reader(file): Reads data from a CSV file.


• csv.writer(file): Writes data to a CSV file.
• csv.DictReader(file): Reads CSV data as dictionaries.
• csv.DictWriter(file, fieldnames): Writes dictionaries to a CSV file.

python
Copy code
import csv
# Reading from a CSV file
with open('data.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row) # Output: Each row as a list

# Writing to a CSV file


with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', '30', 'New York'])

17. logging module:

Provides a flexible framework for emitting log messages from Python programs.

• logging.basicConfig(): Configures the logging system.


• logging.debug(): Logs a message with level DEBUG.
• logging.info(): Logs a message with level INFO.
• logging.error(): Logs a message with level ERROR.

python
Copy code
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.error('This is an error message')

18. shutil module:

Provides high-level file operations like copying and removing files.

• shutil.copy(src, dst): Copies a file from src to dst.


• shutil.move(src, dst): Moves a file or directory to dst.
• shutil.rmtree(path): Deletes a directory and its contents.
• shutil.disk_usage(path): Returns disk usage statistics.

python
Copy code
import shutil
shutil.copy('source.txt', 'destination.txt') # Copy file
shutil.move('source.txt', 'new_location.txt') # Move file
shutil.rmtree('test_dir') # Delete directory

19. zipfile module:

Functions for working with ZIP archives.

• zipfile.ZipFile(file, mode): Creates or reads from a ZIP file.


• zipfile.ZipFile.write(filename): Adds a file to the ZIP archive.
• zipfile.ZipFile.extractall(path): Extracts all files from a ZIP archive.

python
Copy code
import zipfile
# Create a ZIP file
with zipfile.ZipFile('my_files.zip', 'w') as z:
z.write('file1.txt')
z.write('file2.txt')

# Extract from a ZIP file


with zipfile.ZipFile('my_files.zip', 'r') as z:
z.extractall('extracted')

20. glob module:

Provides a function for finding file paths matching a specified pattern.

• glob.glob(pattern): Returns a list of paths that match the specified pattern.


python
Copy code
import glob
print(glob.glob('*.txt')) # Output: List of all text files in the current
directory

21. uuid module:

Provides immutable UUID objects (universally unique identifiers).

• uuid.uuid4(): Generates a random UUID.


• uuid.uuid1(): Generates a UUID based on the host ID and current time.

python
Copy code
import uuid
unique_id = uuid.uuid4()
print(unique_id) # Output: A random UUID like 123e4567-e89b-12d3-a456-
426614174000

22. enum module:

Provides support for enumerations, which are a set of symbolic names bound to unique,
constant values.

• enum.Enum: Base class for creating enumerations.


• enum.auto(): Automatically assign values to enumeration members.

python
Copy code
from enum import Enum, auto
class Color(Enum):
RED = auto()
GREEN = auto()
BLUE = auto()

print(Color.RED) # Output: Color.RED

23. socket module:

Provides low-level networking interface for socket programming.

• socket.socket(): Creates a new socket.


• socket.bind(address): Binds the socket to an address.
• socket.listen(): Enables the server to accept connections.
• socket.connect(address): Connects the socket to the remote address.

python
Copy code
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 8080)) # Bind to localhost on port 8080
s.listen(1) # Listen for incoming connections
These additional modules expand the functionality of Python and make it highly versatile for
tasks such as file handling, networking, logging, and much more.

11. time module:

Functions for working with time-related tasks.

• time.time(): Returns the current time in seconds since the epoch (1970-01-01).

• time.sleep(seconds): Pauses execution for the given number of seconds.

• time.ctime(): Converts a time expressed in seconds to a readable string format.

• time.strftime(format): Returns a string representing the date and time in a specific format.

python

Copy code

import time

print(time.time()) # Output: Current time in seconds since the epoch

time.sleep(2) # Pauses execution for 2 seconds

print(time.ctime()) # Output: Current date and time in a readable format

print(time.strftime('%Y-%m-%d %H:%M:%S')) # Output: Custom formatted date-time

12. calendar module:

Provides functions related to dates and calendars.

• calendar.month(year, month): Returns a string of the month’s calendar.

• calendar.isleap(year): Returns True if the year is a leap year.

• calendar.weekday(year, month, day): Returns the weekday of the given date.

• calendar.calendar(year): Returns a string with the calendar for the entire year.

python

Copy code

import calendar

print(calendar.month(2024, 9)) # Output: September 2024 calendar

print(calendar.isleap(2024)) # Output: True (2024 is a leap year)

print(calendar.weekday(2024, 9, 24)) # Output: Day of the week (0=Monday, 6=Sunday)

print(calendar.calendar(2024)) # Output: Full calendar of 2024

13. subprocess module:

Functions for creating and managing subprocesses.

• subprocess.run(args): Runs a command described by args.


• subprocess.Popen(): Executes a child program in a new process.

• subprocess.call(args): Runs a command described by args and waits for it to complete.

python

Copy code

import subprocess

subprocess.run(['echo', 'Hello, World!']) # Output: Hello, World!

14. hashlib module:

Provides secure hash functions such as SHA-1, SHA-256, and MD5.

• hashlib.md5(): Creates an MD5 hash object.

• hashlib.sha256(): Creates a SHA-256 hash object.

• hashlib.sha1(): Creates a SHA-1 hash object.

python

Copy code

import hashlib

hash_object = hashlib.md5(b'Hello')

print(hash_object.hexdigest()) # Output: MD5 hash of the string 'Hello'

hash_object = hashlib.sha256(b'Hello')

print(hash_object.hexdigest()) # Output: SHA-256 hash of the string 'Hello'

15. configparser module:

Functions for handling configuration files.

• configparser.ConfigParser(): Creates a configuration file parser object.

• config.read(file): Reads a configuration file.

• config.get(section, option): Returns the value of a given option in a section.

python

Copy code

import configparser

config = configparser.ConfigParser()

config.read('config.ini')

print(config.get('Settings', 'theme')) # Output: The value of the 'theme' in 'Settings' section

16. csv module:


Functions to work with CSV (Comma-Separated Values) files.

• csv.reader(file): Reads data from a CSV file.

• csv.writer(file): Writes data to a CSV file.

• csv.DictReader(file): Reads CSV data as dictionaries.

• csv.DictWriter(file, fieldnames): Writes dictionaries to a CSV file.

python

Copy code

import csv

# Reading from a CSV file

with open('data.csv', newline='') as csvfile:

reader = csv.reader(csvfile)

for row in reader:

print(row) # Output: Each row as a list

# Writing to a CSV file

with open('output.csv', 'w', newline='') as csvfile:

writer = csv.writer(csvfile)

writer.writerow(['Name', 'Age', 'City'])

writer.writerow(['Alice', '30', 'New York'])

17. logging module:

Provides a flexible framework for emitting log messages from Python programs.

• logging.basicConfig(): Configures the logging system.

• logging.debug(): Logs a message with level DEBUG.

• logging.info(): Logs a message with level INFO.

• logging.error(): Logs a message with level ERROR.

python

Copy code

import logging

logging.basicConfig(level=logging.DEBUG)

logging.debug('This is a debug message')

logging.info('This is an info message')


logging.error('This is an error message')

18. shutil module:

Provides high-level file operations like copying and removing files.

• shutil.copy(src, dst): Copies a file from src to dst.

• shutil.move(src, dst): Moves a file or directory to dst.

• shutil.rmtree(path): Deletes a directory and its contents.

• shutil.disk_usage(path): Returns disk usage statistics.

python

Copy code

import shutil

shutil.copy('source.txt', 'destination.txt') # Copy file

shutil.move('source.txt', 'new_location.txt') # Move file

shutil.rmtree('test_dir') # Delete directory

19. zipfile module:

Functions for working with ZIP archives.

• zipfile.ZipFile(file, mode): Creates or reads from a ZIP file.

• zipfile.ZipFile.write(filename): Adds a file to the ZIP archive.

• zipfile.ZipFile.extractall(path): Extracts all files from a ZIP archive.

python

Copy code

import zipfile

# Create a ZIP file

with zipfile.ZipFile('my_files.zip', 'w') as z:

z.write('file1.txt')

z.write('file2.txt')

# Extract from a ZIP file

with zipfile.ZipFile('my_files.zip', 'r') as z:

z.extractall('extracted')

20. glob module:

Provides a function for finding file paths matching a specified pattern.


• glob.glob(pattern): Returns a list of paths that match the specified pattern.

python

Copy code

import glob

print(glob.glob('*.txt')) # Output: List of all text files in the current directory

21. uuid module:

Provides immutable UUID objects (universally unique identifiers).

• uuid.uuid4(): Generates a random UUID.

• uuid.uuid1(): Generates a UUID based on the host ID and current time.

python

Copy code

import uuid

unique_id = uuid.uuid4()

print(unique_id) # Output: A random UUID like 123e4567-e89b-12d3-a456-426614174000

22. enum module:

Provides support for enumerations, which are a set of symbolic names bound to unique, constant
values.

• enum.Enum: Base class for creating enumerations.

• enum.auto(): Automatically assign values to enumeration members.

python

Copy code

from enum import Enum, auto

class Color(Enum):

RED = auto()

GREEN = auto()

BLUE = auto()

print(Color.RED) # Output: Color.RED

23. socket module:

Provides low-level networking interface for socket programming.

• socket.socket(): Creates a new socket.


• socket.bind(address): Binds the socket to an address.

• socket.listen(): Enables the server to accept connections.

• socket.connect(address): Connects the socket to the remote address.

python

Copy code

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(('localhost', 8080)) # Bind to localhost on port 8080

s.listen(1) # Listen for incoming connections

These additional modules expand the functionality of Python and make it highly versatile for tasks
such as file handling, networking, logging, and much more.

You might also like