Python Mastery

Daily advice for the modern developer & student

Essential Python Snippets

A collection of copy-paste ready code snippets for common tasks. Save time and code smarter.

File Operations

Reading a File Safely

Using the `with` statement ensures the file is properly closed even if an error occurs.

with open('data.txt', 'r') as f:
    content = f.read()
    print(content)
                

Writing to a File

data = ["Line 1", "Line 2", "Line 3"]
with open('output.txt', 'w') as f:
    for line in data:
        f.write(f"{line}\n")
                

HTTP Requests (JSON)

Fetching data from an API using the standard library (though `requests` library is recommended for more complex tasks).

import urllib.request
import json

url = "https://api.github.com"
with urllib.request.urlopen(url) as response:
    data = json.loads(response.read().decode())
    print(data)
                

Working with JSON

Parsing and stringifying JSON data.

import json

# Python object to JSON string
data = {"name": "Alice", "age": 30}
json_str = json.dumps(data, indent=4)
print(json_str)

# JSON string to Python object
parsed = json.loads(json_str)
print(parsed["name"]) 
                

List Filtering

Filter a list using `filter()` or list comprehension.

numbers = [1, 2, 3, 4, 5, 6]

# Get even numbers
evens = [n for n in numbers if n % 2 == 0]
print(evens) # Output: [2, 4, 6]
                

Welcome Back

End-to-end encrypted messaging

Messages Logout
U
User