Ultimate Python Cheat Sheet - Practical Python For Everyday Tasks - by Jason Roell - Medium
Ultimate Python Cheat Sheet - Practical Python For Everyday Tasks - by Jason Roell - Medium
Become a member
4.96K 43
(My Other Ultimate Guides)
This Cheat Sheet was born out of necessity. Recently, I was tasked with
diving into a new Python project after some time away from the language.
I’ve always appreciated Python’s practical syntax and form. However, being
in Node/Typescript land for some time, I found myself in need of a rapid
refresher on Python’s latest features, best practices, and most impactful
tools. I needed to get back up to speed quickly without getting bogged down
in the minutiae so I compiled this list so that I could reference the tasks and
features I needed to use the most often. Essentially, to grasp the essential
20% of Python that addresses 80% of the programming needs I would
encounter.
I’ve broken up the sections into logical areas that typically work together so
that you can jump to an area you are interested in and find the most related
items to that particular task or subject. This will include file operations, API
interactions, spreadsheet manipulation, mathematical computations, and
working with data structures like lists and dictionaries. Additionally, I’ll
highlight some useful libraries to enhance your Python toolkit that are
prevalent in the domains Python is typically used.
If you think I missed anything that should be included in the Cheat Sheet,
please let me know in the comments and I’ll update the list!
1. Reading a File
To read the entire content of a file:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
2. Writing to a File
To write text to a file, overwriting existing content:
3. Appending to a File
To add text to the end of an existing file:
import os
if os.path.exists('example.txt'):
print('File exists.')
else:
print('File does not exist.')
9. Deleting a File
To safely delete a file if it exists:
import os
if os.path.exists('example.txt'):
os.remove('example.txt')
print('File deleted.')
else:
print('File does not exist.')
import requests
response = requests.get('https://api.example.com/data')
data = response.json() # Assuming the response is JSON
print(data)
import requests
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://api.example.com/search', params=params)
data = response.json()
print(data)
import requests
response = requests.get('https://api.example.com/data')
try:
response.raise_for_status() # Raises an HTTPError if the status is 4xx, 5xx
data = response.json()
print(data)
except requests.exceptions.HTTPError as err:
print(f'HTTP Error: {err}')
import requests
try:
response = requests.get('https://api.example.com/data', timeout=5) # Timeou
data = response.json()
print(data)
except requests.exceptions.Timeout:
print('The request timed out')
import requests
headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
response = requests.get('https://api.example.com/protected', headers=headers)
data = response.json()
print(data)
import requests
response = requests.get('https://api.example.com/data')
response.encoding = 'utf-8' # Set encoding to match the expected response forma
data = response.text
print(data)
import requests
with requests.Session() as session:
session.headers.update({'Authorization': 'Bearer YOUR_ACCESS_TOKEN'})
response = session.get('https://api.example.com/data')
print(response.json())
Open in app
9. Handling Redirects
Search Write
To handle or disable redirects in requests:
import requests
response = requests.get('https://api.example.com/data', allow_redirects=False)
print(response.status_code)
import requests
response = requests.get('https://api.example.com/large-data', stream=True)
for chunk in response.iter_content(chunk_size=1024):
process(chunk) # Replace 'process' with your actual processing function
1. Creating a List
To conjure a list into being:
elements.append('Aether')
index_of_air = elements.index('Air')
7. List Slicing
To slice a list, obtaining a sub-list:
8. List Comprehension
To create a new list by applying an expression to each element of an existing
one:
9. Sorting a List
To sort a list in ascending order (in-place):
elements.sort()
elements.reverse()
1. Creating a Dictionary
To forge a new dictionary:
if 'Helium' in elements:
print('Helium is present')
8. Dictionary Comprehension
To conjure a new dictionary through an incantation over an iterable:
9. Merging Dictionaries
To merge two or more dictionaries, forming a new alliance of their entries:
import os
# Craft a path compatible with the underlying OS
path = os.path.join('mystic', 'forest', 'artifact.txt')
# Retrieve the tome's directory
directory = os.path.dirname(path)
# Unveil the artifact's name
artifact_name = os.path.basename(path)
import os
contents = os.listdir('enchanted_grove')
print(contents)
3. Creating Directories
To conjure new directories within the fabric of the filesystem:
import os
# create a single directory
os.mkdir('alchemy_lab')
# create a hierarchy of directories
os.makedirs('alchemy_lab/potions/elixirs')
import os
# remove a file
os.remove('unnecessary_scroll.txt')
# remove an empty directory
os.rmdir('abandoned_hut')
# remove a directory and its contents
import shutil
shutil.rmtree('cursed_cavern')
import subprocess
# Invoke the 'echo' incantation
result = subprocess.run(['echo', 'Revealing the arcane'], capture_output=True, t
print(result.stdout)
import os
# Read the 'PATH' variable
path = os.environ.get('PATH')
# Create a new environment variable
os.environ['MAGIC'] = 'Arcane'
import os
# Traverse to the 'arcane_library' directory
os.chdir('arcane_library')
import os
# Check if a path exists
exists = os.path.exists('mysterious_ruins')
# Ascertain if the path is a directory
is_directory = os.path.isdir('mysterious_ruins')
# Determine if the path is a file
is_file = os.path.isfile('ancient_manuscript.txt')
import tempfile
# Create a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False)
print(temp_file.name)
# Erect a temporary directory
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
import os
import platform
# Discover the operating system
os_name = os.name # 'posix', 'nt', 'java'
# Unearth detailed system information
system_info = platform.system() # 'Linux', 'Windows', 'Darwin'
2. Printing to STDOUT
To print messages to the console:
3. Formatted Printing
To weave variables into your messages with grace and precision:
name = "Merlin"
age = 300
print(f"{name}, of {age} years, speaks of forgotten lore.")
import sys
for line in sys.stdin:
print(f"Echo from the void: {line.strip()}")
5. Writing to STDERR
To send message to STDERR:
import sys
sys.stderr.write("Beware! The path is fraught with peril.\n")
6. Redirecting STDOUT
To redirect the STDOUT:
import sys
original_stdout = sys.stdout # Preserve the original STDOUT
with open('mystic_log.txt', 'w') as f:
sys.stdout = f # Redirect STDOUT to a file
print("This message is inscribed within the mystic_log.txt.")
sys.stdout = original_stdout # Restore STDOUT to its original glory
7. Redirecting STDERR
Redirecting STDERR:
import sys
with open('warnings.txt', 'w') as f:
sys.stderr = f # Redirect STDERR
print("This warning is sealed within warnings.txt.", file=sys.stderr)
8. Prompting for Passwords
To prompt for passwords:
import getpass
secret_spell = getpass.getpass("Whisper the secret spell: ")
import sys
# The script's name is the first argument, followed by those passed by the invok
script, first_arg, second_arg = sys.argv
print(f"Invoked with the sacred tokens: {first_arg} and {second_arg}")
import argparse
parser = argparse.ArgumentParser(description="Invoke the ancient scripts.")
parser.add_argument('spell', help="The spell to cast")
parser.add_argument('--power', type=int, help="The power level of the spell")
args = parser.parse_args()
print(f"Casting {args.spell} with power {args.power}")
Working With Mathematical Operations and Permutations
sum = 7 + 3 # Addition
difference = 7 - 3 # Subtraction
product = 7 * 3 # Multiplication
quotient = 7 / 3 # Division
remainder = 7 % 3 # Modulus (Remainder)
power = 7 ** 3 # Exponentiation
3. Mathematical Functions
Common math functions:
import math
root = math.sqrt(16) # Square root
logarithm = math.log(100, 10) # Logarithm base 10 of 100
sine = math.sin(math.pi / 2) # Sine of 90 degrees (in radians)
4. Generating Permutations
Easy way to generate permutations from a given set:
5. Generating Combinations
Easy way to generate combinations:
import random
num = random.randint(1, 100) # Generate a random integer between 1 and 100
8. Statistical Functions
To get Average, Median, and Standard Deviation:
import statistics
data = [1, 2, 3, 4, 5]
mean = statistics.mean(data) # Average
median = statistics.median(data) # Median
stdev = statistics.stdev(data) # Standard Deviation
9. Trigonometric Functions
To work with trigonometry:
import math
angle_rad = math.radians(60) # Convert 60 degrees to radians
cosine = math.cos(angle_rad) # Cosine of the angle
10. Handling Infinity and NaN
To work with Infinity and NaN:
import math
infinity = math.inf # Representing infinity
not_a_number = math.nan # Representing a non-number (NaN)
1. Establishing a Connection
To create a connection to a Postgres Database:
import psycopg2
connection = psycopg2.connect(
dbname='your_database',
user='your_username',
password='your_password',
host='your_host'
)
2. Creating a Cursor
To create a database cursor, enabling the traversal and manipulation of
records:
cursor = connection.cursor()
3. Executing a Query
Selecting data from Database:
records = cursor.fetchall()
for record in records:
print(record)
5. Inserting Records
To insert data into tables in a database:
6. Updating Records
To alter the records:
cursor.execute("UPDATE your_table SET column1 = %s WHERE column2 = %s", ('new_va
connection.commit()
7. Deleting Records
To delete records from the table:
8. Creating a Table
To create a new table, defining its structure:
cursor.execute("""
CREATE TABLE your_new_table (
id SERIAL PRIMARY KEY,
column1 VARCHAR(255),
column2 INTEGER
)
""")
connection.commit()
9. Dropping a Table
To drop a table:
cursor.execute("DROP TABLE if exists your_table")
connection.commit()
try:
cursor.execute("your first transactional query")
cursor.execute("your second transactional query")
connection.commit() # Commit if all is well
except Exception as e:
connection.rollback() # Rollback in case of any issue
print(f"An error occurred: {e}")
import asyncio
async def fetch_data():
print("Fetching data...")
await asyncio.sleep(2) # Simulate an I/O operation
print("Data retrieved.")
4. Creating Tasks
To dispatch tasks:
5. Asynchronous Iteration
To traverse through asynchronously, allowing time for other functions in
between:
8. Asynchronous Generators
To create async generators, each arriving in its own time:
9. Using Semaphores
To limit the number of concurrent tasks:
1. Creating a Socket
To create a socket for network communication:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
3. Sending Data
To dispatch data through the network to a connected entity:
s.sendall(b'Hello, server')
4. Receiving Data
To receive data from the network:
5. Closing a Socket
To gracefully close the socket, severing the network link:
s.close()
7. Accepting Connections
To accept and establish a network link:
s.setblocking(False)
import socket
import netifaces
for interface in netifaces.interfaces():
addr = netifaces.ifaddresses(interface).get(netifaces.AF_INET)
if addr:
print(f"Interface: {interface}, Address: {addr[0]['addr']}")
1. Creating a DataFrame
To create a DataFrame with your own columns and data:
import pandas as pd
data = {
'Element': ['Earth', 'Water', 'Fire', 'Air'],
'Symbol': ['🜃', '🜄', '🜂', '🜁']
}
df = pd.DataFrame(data)
print(df.head())
4. Selecting Columns
To select specific columns from dataframe:
symbols = df['Symbol']
5. Filtering Rows
To sift through the DataFrame, selecting rows that meet your criteria:
8. Merging DataFrames
To weave together two DataFrames, joining them by a shared key:
df.fillna(value='Unknown', inplace=True)
import numpy as np
array = np.array([1, 2, 3, 4, 5])
5. Reshaping an Array
To transmute the shape of an array, altering its dimensions:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
sum = a + b # Element-wise addition
difference = b - a # Element-wise subtraction
product = a * b # Element-wise multiplication
7. Matrix Multiplication
Basic dot product Operation:
9. Boolean Indexing
To filter the elements of an array through the sieve of conditionals:
mean = np.mean(a)
maximum = np.max(a)
sum = np.sum(a)
plt.plot(x, y)
plt.title('Growth Over Time')
plt.xlabel('Time')
plt.ylabel('Growth')
plt.show()
z = [2, 3, 4, 5, 6]
plt.plot(x, y)
plt.plot(x, z)
plt.show()
6. Creating Subplots
To create subplots:
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
plt.hist(data, bins=4)
plt.show()
8. Adding a Legend
To create a legend for the plot:
plt.plot(x, y, label='Growth')
plt.plot(x, z, label='Decay')
plt.legend()
plt.show()
9. Customizing Ticks
To create your own marks upon the axes, defining the scale of your values:
plt.plot(x, y)
plt.xticks([1, 2, 3, 4, 5], ['One', 'Two', 'Three', 'Four', 'Five'])
plt.yticks([0, 5, 10, 15, 20, 25], ['0', '5', '10', '15', '20', '25+'])
plt.show()
1. Loading a Dataset
To work with datasets for your ML experiments
3. Training a Model
Training a ML Model using RandomForestClassifier:
4. Making Predictions
To access the model predictions:
predictions = model.predict(X_test)
6. Using Cross-Validation
To use Cross-Validation:
7. Feature Scaling
To create the appropriate scales of your features, allowing the model to learn
more effectively:
9. Pipeline Creation
To streamline your data processing and modeling steps, crafting a seamless
flow:
import joblib
# Saving the model
joblib.dump(model, 'model.joblib')
# Loading the model
loaded_model = joblib.load('model.joblib')
import plotly.graph_objs as go
import plotly.io as pio
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'))
pio.show(fig)
5. Creating a Histogram
To create a Histogram:
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
fig = go.Figure(data=go.Histogram(x=data))
pio.show(fig)
7. Creating Heatmaps
To create a heatmap:
import numpy as np
z = np.random.rand(10, 10) # Generate random data
fig = go.Figure(data=go.Heatmap(z=z))
pio.show(fig)
9. Creating Subplots
To create a subplot:
import pandas as pd
dates = pd.date_range('20230101', periods=5)
values = [10, 11, 12, 13, 14]
fig = go.Figure(data=go.Scatter(x=dates, y=values, mode='lines+markers'))
pio.show(fig)
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
print(f"Year: {year}, Month: {month}, Day: {day}, Hour: {hour}, Minute: {minute}
weekday = now.strftime("%A")
print(f"Today is: {weekday}")
timestamp = datetime.timestamp(now)
print(f"Current timestamp: {timestamp}")
# Converting a timestamp back to a datetime
date_from_timestamp = datetime.fromtimestamp(timestamp)
print(f"Date from timestamp: {date_from_timestamp}")
import math
transformed = [math.sqrt(x) for x in range(1, 6)]
print(transformed) # Square roots of numbers from 1 to 5
8. Using Lambda with Map and Filter
To map and filter lists:
class Wizard:
def __init__(self, name, power):
self.name = name
self.power = power
def cast_spell(self):
print(f"{self.name} casts a spell with power {self.power}!")
2. Creating an Instance
To create an instance of your class:
3. Invoking Methods
To call methods on instance of class:
merlin.cast_spell()
4. Inheritance
Subclassing:
class ArchWizard(Wizard):
def __init__(self, name, power, realm):
super().__init__(name, power)
self.realm = realm
def summon_familiar(self):
print(f"{self.name} summons a familiar from the {self.realm} realm.")
5. Overriding Methods
To overide base classes:
class Sorcerer(Wizard):
def cast_spell(self):
print(f"{self.name} casts a powerful dark spell!")
6. Polymorphism
To interact with different forms through a common interface:
def unleash_magic(wizard):
wizard.cast_spell()
unleash_magic(merlin)
unleash_magic(Sorcerer("Voldemort", 90))
7. Encapsulation
To use information hiding:
class Alchemist:
def __init__(self, secret_ingredient):
self.__secret = secret_ingredient
def reveal_secret(self):
print(f"The secret ingredient is {self.__secret}")
8. Composition
To assemble Objects from simpler ones:
class Spellbook:
def __init__(self, spells):
self.spells = spells
class Mage:
def __init__(self, name, spellbook):
self.name = name
self.spellbook = spellbook
class Enchanter:
@staticmethod
def enchant(item):
print(f"{item} is enchanted!")
@classmethod
def summon(cls):
print("A new enchanter is summoned.")
10. Properties and Setters
To elegantly manage access to an entity’s attributes, guiding their use and
protection:
class Elementalist:
def __init__(self, element):
self._element = element
@property
def element(self):
return self._element
@element.setter
def element(self, value):
if value in ["Fire", "Water", "Earth", "Air"]:
self._element = value
else:
print("Invalid element!")
1. Basic Decorator
To create a simple decorator that wraps a function:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before call")
result = func(*args, **kwargs)
print("After call")
return result
return wrapper
@my_decorator
def greet(name):
print(f"Hello {name}")
greet("Alice")
3. Using functools.wraps
To preserve the metadata of the original function when decorating:
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
"""Wrapper function"""
return func(*args, **kwargs)
return wrapper
@my_decorator
def greet(name):
"""Greet someone"""
print(f"Hello {name}")
4. Class Decorator
To create a decorator using a class:
class MyDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("Before call")
self.func(*args, **kwargs)
print("After call")
@MyDecorator
def greet(name):
print(f"Hello {name}")
greet("Alice")
def repeat(times):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello")
say_hello()
6. Method Decorator
To apply a decorator to a method within a class:
def method_decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
print("Method Decorator")
return func(self, *args, **kwargs)
return wrapper
class MyClass:
@method_decorator
def greet(self, name):
print(f"Hello {name}")
obj = MyClass()
obj.greet("Alice")
7. Stacking Decorators
To apply multiple decorators to a single function:
@my_decorator
@repeat(2)
def greet(name):
print(f"Hello {name}")
greet("Alice")
def smart_decorator(arg=None):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if arg:
print(f"Argument: {arg}")
return func(*args, **kwargs)
return wrapper
if callable(arg):
return decorator(arg)
return decorator
@smart_decorator
def no_args():
print("No args")
@smart_decorator("With args")
def with_args():
print("With args")
no_args()
with_args()
class MyClass:
@classmethod
@my_decorator
def class_method(cls):
print("Class method called")
MyClass.class_method()
class MyClass:
@staticmethod
@my_decorator
def static_method():
print("Static method called")
MyClass.static_method()
query = gql('''
{
allWizards {
id
name
power
}
}
''')
result = client.execute(query)
print(result)
query = gql('''
query GetWizards($element: String!) {
wizards(element: $element) {
id
name
}
}
''')
params = {"element": "Fire"}
result = client.execute(query, variable_values=params)
print(result)
4. Mutations
To create and execute a mutation:
mutation = gql('''
mutation CreateWizard($name: String!, $element: String!) {
createWizard(name: $name, element: $element) {
wizard {
id
name
}
}
}
''')
params = {"name": "Gandalf", "element": "Light"}
result = client.execute(mutation, variable_values=params)
print(result)
5. Handling Errors
Error handling:
6. Subscriptions
Working with Subscriptions:
subscription = gql('''
subscription {
wizardUpdated {
id
name
power
}
}
''')
for result in client.subscribe(subscription):
print(result)
7. Fragments
Working with Fragments:
query = gql('''
fragment WizardDetails on Wizard {
name
power
}
query {
allWizards {
...WizardDetails
}
}
''')
result = client.execute(query)
print(result)
8. Inline Fragments
To tailor the response based on the type of the object returned:
query = gql('''
{
search(text: "magic") {
__typename
... on Wizard {
name
power
}
... on Spell {
name
effect
}
}
}
''')
result = client.execute(query)
print(result)
9. Using Directives
To dynamically include or skip fields in your queries based on conditions:
query = gql('''
query GetWizards($withPower: Boolean!) {
allWizards {
name
power @include(if: $withPower)
}
}
''')
params = {"withPower": True}
result = client.execute(query, variable_values=params)
print(result)
transport = RequestsHTTPTransport(url='https://your-graphql-endpoint.com/graphql
client = Client(transport=transport, fetch_schema_from_transport=True)
query1 = gql('query { wizard(id: "1") { name } }')
query2 = gql('query { allSpells { name } }')
import re
text = "Search this string for patterns."
match = re.search(r"patterns", text)
if match:
print("Pattern found!")
pattern = re.compile(r"patterns")
match = pattern.search(text)
6. Splitting a String
To split a string by occurrences of a pattern:
9. Non-Capturing Groups
To define groups without capturing them:
html = "<body><h1>Title</h1></body>"
match = re.search(r"<.*?>", html)
if match:
print(match.group()) # Matches '<body>'
pattern = re.compile(r"""
\b # Word boundary
\w+ # One or more word characters
\s # Space
""", re.VERBOSE)
match = pattern.search(text)
1. Concatenating Strings
To join strings together:
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message)
s = "Python"
print(s.upper()) # Uppercase
print(s.lower()) # Lowercase
print(s.title()) # Title Case
s = "filename.txt"
print(s.startswith("file")) # True
print(s.endswith(".txt")) # True
s = "split,this,string"
words = s.split(",") # Split string into list
joined = " ".join(words) # Join list into string
print(words)
print(joined)
s = "Hello world"
new_s = s.replace("world", "Python")
print(new_s)
s = "characters"
for char in s:
print(char) # Prints each character on a new line
11. String Methods — isdigit , isalpha , isalnum
print("123".isdigit()) # True
print("abc".isalpha()) # True
print("abc123".isalnum())# True
s = "slice me"
sub = s[2:7] # From 3rd to 7th character
print(sub)
s = "length"
print(len(s)) # 6
path = r"C:\User\name\folder"
print(path)
import requests
url = 'https://example.com'
response = requests.get(url)
html = response.text
base_url = "https://example.com/page/"
for page in range(1, 6): # For 5 pages
page_url = base_url + str(page)
response = requests.get(page_url)
# Process each page's content
# Find the URL of the AJAX request (using browser's developer tools) and fetch i
ajax_url = 'https://example.com/ajax_endpoint'
data = requests.get(ajax_url).json() # Assuming the response is JSON
rp = RobotFileParser()
rp.set_url('https://example.com/robots.txt')
rp.read()
can_scrape = rp.can_fetch('*', url)
session = requests.Session()
session.get('https://example.com/login')
session.cookies.set('key', 'value') # Set cookies, if needed
response = session.get('https://example.com/protected_page')
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # Raises an error for bad status codes
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
import aiohttp
import asyncio
import csv
1. Installing a Package
To summon a library from the vast repositories, incorporating its power into
your environment:
pip list
3. Upgrading a Package
To imbue an installed library with enhanced powers and capabilities,
elevating it to its latest form:
4. Uninstalling a Package
To uninstall a package:
# On Unix or MacOS
source venv/bin/activate
import os
current_directory = os.getcwd() # Get the current working directory
import sys
sys.exit() # Exit the script
import math
result = math.sqrt(16) # Square root
import random
number = random.randint(1, 10) # Random integer between 1 and 10
import json
json_string = json.dumps({'name': 'Alice', 'age': 30}) # Dictionary to JSON str
7. re - Regular Expressions
To work with regular expressions:
import re
match = re.search('Hello', 'Hello, world!') # Search for 'Hello' in the string
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'<html><head><title>Python HTTP
Server</title></head>')
self.wfile.write(b'<body><h1>Hello from a simple Python HTTP
server!</h1></body></html>')
def run(server_class=HTTPServer,
handler_class=SimpleHTTPRequestHandler):
server_address = ('', 8000) # Serve on all addresses, port 8000
httpd = server_class(server_address, handler_class)
print("Server starting on port 8000...")
httpd.serve_forever()
if __name__ == '__main__':
run()
import subprocess
subprocess.run(['ls', '-l']) # Run the 'ls -l' command
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a TCP/IP socket
import argparse
parser = argparse.ArgumentParser(description="Process some integers.")
args = parser.parse_args()
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
import itertools
for combination in itertools.combinations('ABCD', 2):
print(combination)
import hashlib
hash_object = hashlib.sha256(b'Hello World')
hex_dig = hash_object.hexdigest()
22. csv - CSV File Reading and Writing
To read from and write to CSV files:
import csv
with open('file.csv', mode='r') as infile:
reader = csv.reader(infile)
import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
import sqlite3
conn = sqlite3.connect('example.db')
import pickle
serialized_obj = pickle.dumps(obj)
import time
time.sleep(1) # Sleep for 1 second
29. calendar - General Calendar-related Functions
To work with calendars:
import calendar
print(calendar.month(2023, 1)) # Print the calendar for January 2023
import shutil
shutil.copyfile('source.txt', 'dest.txt')
import tempfile
temp = tempfile.TemporaryFile()
import bz2
compressed = bz2.compress(b'your data here')
import gzip
with gzip.open('file.txt.gz', 'wt') as f:
f.write('your data here')
36. ssl - TLS/SSL Wrapper for Socket Objects
To handle TLS/SSL encryption and peer authentication for network sockets:
import ssl
ssl.wrap_socket(sock)
import imaplib
mail = imaplib.IMAP4_SSL('imap.example.com')
import smtplib
server = smtplib.SMTP('smtp.example.com', 587)
import base64
encoded_data = base64.b64encode(b'data to encode')
import difflib
diff = difflib.ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
'ore\ntree\nemu\n'.splitlines(keepends=True))
print(''.join(diff))
import gettext
gettext.install('myapp')
43. locale - Internationalization Services
To access a database of culture-specific data formats:
import locale
locale.setlocale(locale.LC_ALL, '')
import secrets
secure_token = secrets.token_hex(16)
import uuid
unique_id = uuid.uuid4()
import tarfile
with tarfile.open('sample.tar.gz', 'w:gz') as tar:
tar.add('sample.txt')
Well, that’s all I have for now. I hope this list helps you get up to speed fast. If
you like it, please share or give it a like (it helps a lot!).
Stackademic 🎓
Thank you for reading until the end. Before you go:
3.3K Followers
AI Practitioner/Software Engineer (jasonroell.com) looking for the hardest problems to
solve. (https://www.linkedin.com/in/jason-roell-47830817/)
17 min read · Apr 18, 2024 12 min read · Feb 19, 2024
16 1.1K 12
712 8 6.6K 15
50 Coding Laws That Would Make You Need To Learn AI in 2024! (And
You A Decent Programmer. Here Is Your Roadmap)
Follow these laws or get fired. Photo by Maximalfocus on Unsplash
1.91K 23 2.3K 54
Lists
Predictive Modeling w/ Coding & Development
Python 11 stories · 638 saves
20 stories · 1250 saves
You’re Decent At Python If You Can How I Create Passive Income With
Answer These 7 Questions… No Money
# No cheating pls!! many ways to start a passive income today
11.2K 152