Essential Python Snippets
A collection of copy-paste ready code snippets for common tasks. Save time and code smarter.
Daily advice for the modern developer & student
A collection of copy-paste ready code snippets for common tasks. Save time and code smarter.
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)
data = ["Line 1", "Line 2", "Line 3"]
with open('output.txt', 'w') as f:
for line in data:
f.write(f"{line}\n")
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)
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"])
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]