🚀 Boost your file handling with
Tired of fiddling with string concatenations for paths?
Why you’ll love it:
- No more
- Works the same on Windows, macOS, Linux.
- Handy methods like
Give it a try and say goodbye to brittle path strings! 🎉
pathlib! Tired of fiddling with string concatenations for paths?
pathlib lets you treat file paths like objects – safe, readable, and cross‑platform.from pathlib import Path
# 📁 Build a path to "data/report.txt" inside the user's home folder
home = Path.home()
report_path = home / "data" / "report.txt"
# ✅ Check if it exists, read its content, and print the first line
if report_path.is_file():
first_line = report_path.read_text().splitlines()[0]
print(f"🗒️ First line: {first_line}")
else:
print("❌ File not found!")
Why you’ll love it:
- No more
os.path.join headaches. - Works the same on Windows, macOS, Linux.
- Handy methods like
.is_file(), .read_text(), .write_text() keep code clean.Give it a try and say goodbye to brittle path strings! 🎉
💡 Quick tip: the Walrus operator (
What’s happening?
-
- The same expression is immediately checked with
No extra
:=) lets you assign and test a value in a single line. Great for reading input, looping over data, or any situation where you’d otherwise need two statements.# Read numbers until a non‑numeric line appears
while (line := input("Enter a number (or anything else to stop): ")) .isdigit():
number = int(line)
print(f"✅ You entered {number}")
print("🚪 Done!")
What’s happening?
-
line := input(...) captures the user’s input. - The same expression is immediately checked with
.isdigit(). No extra
line = input(...) line, no duplicate calls—cleaner and faster to write. Give it a try in your next script! 🚀💡 Silently ignore the errors you expect – without a try/except clutter
When you have a piece of code that may raise a known exception (e.g., trying to delete a file that might already be gone), wrapping it in a full
✅ Why you’ll love it
- No extra indentation levels – your main logic stays front‑and‑center.
- Explicit about which exception is being ignored, so it’s safe and self‑documenting.
- Works with any exception type, even custom ones.
Give it a try next time you need a “try‑and‑forget” cleanup! 🚀
When you have a piece of code that may raise a known exception (e.g., trying to delete a file that might already be gone), wrapping it in a full
try/except block can feel noisy. contextlib.suppress does the same thing in a single line and keeps the flow readable.from contextlib import suppress
import os
# Remove a temp file if it exists – ignore the FileNotFoundError otherwise
with suppress(FileNotFoundError):
os.remove('temp_data.json')
✅ Why you’ll love it
- No extra indentation levels – your main logic stays front‑and‑center.
- Explicit about which exception is being ignored, so it’s safe and self‑documenting.
- Works with any exception type, even custom ones.
Give it a try next time you need a “try‑and‑forget” cleanup! 🚀
❤1
🚀 One‑liner to count & rank items in a list
Ever needed a quick frequency report (e.g., most used words, top error codes) without writing a loop? 🎯
Why it’s cool
- Fast – implemented in C, O(n) time.
- Readable – the intent is obvious at a glance.
- Flexible –
Next time you need a quick tally, reach for
Ever needed a quick frequency report (e.g., most used words, top error codes) without writing a loop? 🎯
collections.Counter does it in a single line and gives you handy helpers like most_common.from collections import Counter
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
top = Counter(data).most_common(2) # → [('apple', 3), ('banana', 2)]
print(top)
Why it’s cool
- Fast – implemented in C, O(n) time.
- Readable – the intent is obvious at a glance.
- Flexible –
most_common() can return all items or just the top N.Next time you need a quick tally, reach for
Counter and skip the manual dictionary gymnastics! 🌟💡 Merge dictionaries in one clean line – the
When you need a base config and want to overlay user‑provided values, the classic
Want to update in place? Use the in‑place version:
No loops, no
| operator (Python 3.9+)When you need a base config and want to overlay user‑provided values, the classic
dict.update() mutates the original. With the new pipe syntax you can keep both dictionaries untouched and get a brand‑new combined mapping.# default settings
default_cfg = {
"host": "localhost",
"port": 8000,
"debug": False,
}
# values supplied by the user (maybe from a CLI or a JSON file)
user_cfg = {
"port": 8080,
"debug": True,
}
# 👇 merge → user_cfg wins on overlapping keys
merged_cfg = default_cfg | user_cfg
print(merged_cfg)
# {'host': 'localhost', 'port': 8080, 'debug': True}
Want to update in place? Use the in‑place version:
default_cfg |= user_cfg # modifies default_cfg
No loops, no
copy() calls – just a single, readable operator. Perfect for settings, API payloads, or any situation where you blend two maps. 🚀💡 Keep the order, drop the duplicates – in one line
Got a list with repeating items and need the first occurrence of each element, preserving the original order?
Python’s
* How it works
*
* Converting the dict back to a list (
🔧 When to use: cleaning up CSV columns, de‑duplicating user input, or any place you need “unique but ordered” without pulling in
Give it a try – it’s both fast and readable! 🚀
Got a list with repeating items and need the first occurrence of each element, preserving the original order?
Python’s
dict (since 3.7) remembers insertion order, so you can turn the sequence into keys and back again:>>> data = ["apple", "banana", "apple", "orange", "banana", "grape"]
>>> unique = list(dict.fromkeys(data))
>>> unique
['apple', 'banana', 'orange', 'grape']
* How it works
*
dict.fromkeys(data) creates a dict where each list item becomes a key – duplicates are automatically discarded. * Converting the dict back to a list (
list(...)) gives you the values in the exact order they first appeared.🔧 When to use: cleaning up CSV columns, de‑duplicating user input, or any place you need “unique but ordered” without pulling in
OrderedDict or extra loops. Give it a try – it’s both fast and readable! 🚀


