Python Snippets You'll Actually Use

Python is beloved for its readability and the ability to accomplish a lot with very little code. This collection covers real-world tasks you'll encounter regularly — file I/O, data manipulation, date handling, and Pythonic patterns that every developer should have in their toolkit.

1. Read and Write Files

# Read a file into a string
with open('data.txt', 'r') as f:
    content = f.read()

# Write to a file (overwrites existing content)
with open('output.txt', 'w') as f:
    f.write('Hello, World!')

# Append to a file
with open('log.txt', 'a') as f:
    f.write('New log entry\n')

2. Read a CSV File with the Standard Library

import csv

with open('data.csv', newline='') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['name'], row['email'])

3. Flatten a Nested List

nested = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat = [item for sublist in nested for item in sublist]
# [1, 2, 3, 4, 5, 6, 7, 8]

4. Remove Duplicates While Preserving Order

def remove_duplicates(lst):
    seen = set()
    return [x for x in lst if not (x in seen or seen.add(x))]

items = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
unique = remove_duplicates(items)
# [3, 1, 4, 5, 9, 2, 6]

5. Merge and Sort Dictionaries

# Merge two dicts (Python 3.9+)
defaults = {'color': 'blue', 'size': 'medium'}
overrides = {'color': 'red'}
merged = defaults | overrides
# {'color': 'red', 'size': 'medium'}

# Sort a list of dicts by a key
users = [{'name': 'Charlie', 'age': 28}, {'name': 'Alice', 'age': 34}]
sorted_users = sorted(users, key=lambda u: u['age'])

6. Work with Dates and Times

from datetime import datetime, timedelta

now = datetime.now()
today_str = now.strftime('%Y-%m-%d')          # '2025-04-28'
tomorrow = now + timedelta(days=1)

# Parse a date string
parsed = datetime.strptime('2025-01-15', '%Y-%m-%d')

7. Count Element Occurrences

from collections import Counter

words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
counts = Counter(words)
# Counter({'apple': 3, 'banana': 2, 'cherry': 1})

most_common = counts.most_common(2)
# [('apple', 3), ('banana', 2)]

8. Safely Get Nested Dictionary Values

data = {'user': {'address': {'city': 'Berlin'}}}

# Using chained .get() — no KeyError risk
city = data.get('user', {}).get('address', {}).get('city', 'Unknown')
# 'Berlin'

9. Run Shell Commands from Python

import subprocess

result = subprocess.run(['ls', '-la'], capture_output=True, text=True)
print(result.stdout)

10. Create a Simple HTTP Request

import urllib.request
import json

url = 'https://api.github.com/repos/python/cpython'
with urllib.request.urlopen(url) as response:
    data = json.loads(response.read())
    print(data['stargazers_count'])

11. Generate a Random Password

import secrets
import string

def generate_password(length=16):
    alphabet = string.ascii_letters + string.digits + '!@#$%^&*()'
    return ''.join(secrets.choice(alphabet) for _ in range(length))

print(generate_password())  # e.g., 'aK3!vN#pLq8@mZeW'

12. Time a Block of Code

import time

start = time.perf_counter()
# ... your code here ...
elapsed = time.perf_counter() - start
print(f'Completed in {elapsed:.4f}s')

Quick Reference

TaskModule / Feature
File I/OBuilt-in open()
CSV parsingcsv
Counting elementscollections.Counter
Dates & timesdatetime
Secure random valuessecrets
Shell commandssubprocess
HTTP requestsurllib.request
Performance timingtime.perf_counter()

All of these snippets use only Python's standard library — no third-party packages required. Bookmark this page and reach for it whenever you need a quick, reliable solution without hunting through documentation.