Python code examples
20 short, tested snippets. Pick one to see the code with notes, or search Zest for something specific, such as “python read a file”.
- Read a filewith open("data.txt", encoding="utf-8") as f:
- Write a filewith open("out.txt", "w", encoding="utf-8") as f:
- List comprehensionsquares = [x * x for x in range(10)]
- Loop over a dictionaryd = {"a": 1, "b": 2}
- Sort a list of dictionariespeople = [{"name": "Ann", "age": 31}, {"name": "Bob", "age": 25}]
- Handle exceptionstry:
- HTTP GET requestimport requests
- HTTP POST JSONimport requests
- Parse and write JSONimport json
- Define a classclass Dog:
- Read a CSV fileimport csv
- Current date and time, formattedfrom datetime import datetime, timedelta, timezone
- Command-line argumentsimport argparse
- Create a virtual environmentpython -m venv .venv
- enumerate and zipnames = ["a", "b", "c"]
- Read an environment variableimport os
- Remove duplicates from a listitems = [3, 1, 3, 2, 1]
- Async / await basicsimport asyncio
- Regular expressionsimport re
- Hello worldprint("Hello, World!")