Tiny Scripts, Big Time Savings
These are the Python one-liners I actually use in production — not clever tricks for interviews, but practical shortcuts that save real time.
File Operations
# Read entire file
content = open("data.txt").read()
# Read lines into list (stripped)
lines = [l.strip() for l in open("data.txt")]
# Write list to file
open("output.txt", "w").write("\n".join(lines))
# Count lines in a file
line_count = sum(1 for _ in open("huge_file.log"))
# Find all .py files recursively
from pathlib import Path
py_files = list(Path(".").rglob("*.py"))
Data Processing
# CSV to list of dicts
import csv
data = list(csv.DictReader(open("data.csv")))
# JSON file to dict
import json
config = json.loads(open("config.json").read())
# Flatten nested list
flat = [x for sublist in nested for x in sublist]
# Remove duplicates preserving order
unique = list(dict.fromkeys(items))
# Group items
from itertools import groupby
groups = {k: list(v) for k, v in groupby(sorted(items, key=key_fn), key=key_fn)}
Web Requests
# Quick GET request
import requests
data = requests.get("https://api.openalex.org/works?search=python&per_page=3").json()
# Download a file
open("file.zip", "wb").write(requests.get("https://example.com/file.zip").content)
# Check if URL is alive
is_alive = requests.head("https://example.com", timeout=5).status_code == 200
String Processing
# Extract emails from text
import re
emails = re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text)
# Extract URLs from text
urls = re.findall(r"https?://[\S]+", text)
# Clean whitespace
clean = " ".join(text.split())
# Title case
title = "hello world from python".title() # "Hello World From Python"
# Reverse a string
reversed_str = text[::-1]
System & CLI
# Quick HTTP server (run from terminal)
# python3 -m http.server 8000
# Quick JSON formatting
# echo '{"a":1}' | python3 -m json.tool
# Get current timestamp
from datetime import datetime
now = datetime.now().isoformat()
# Timer decorator
import time
timer = lambda f: lambda *a, **k: (t := time.time(), r := f(*a, **k), print(f"{f.__name__}: {time.time()-t:.2f}s"))[1]
Data Analysis (with DuckDB)
# Query CSV with SQL — one line
import duckdb
result = duckdb.sql("SELECT category, COUNT(*) FROM 'sales.csv' GROUP BY 1 ORDER BY 2 DESC").df()
# Quick stats
stats = duckdb.sql("SELECT COUNT(*), AVG(price), MIN(price), MAX(price) FROM 'products.csv'").fetchone()
API Calls
# Search academic papers (no key needed)
papers = requests.get("https://api.openalex.org/works", params={"search": "AI", "per_page": 5}).json()["results"]
# Get weather (no key needed)
weather = requests.get("https://api.open-meteo.com/v1/forecast", params={"latitude": 40.71, "longitude": -74.01, "current_weather": True}).json()["current_weather"]
# Get exchange rate (no key needed)
rate = requests.get("https://open.er-api.com/v6/latest/USD").json()["rates"]["EUR"]
The Pattern
Every one-liner follows the same principle: import → call → result in one expression.
No boilerplate. No classes. No 50 lines of setup for a simple task.
When it gets complex, I move to a proper script. But for quick tasks? These save me hours every week.
All My Scripts
I maintain a collection of ready-to-run Python scripts:
python-data-scripts — 10+ scripts for APIs, scraping, and data processing.
What Python one-liners do you use daily? Share your favorites — I'll add the best ones to the collection.
I write about practical Python and free APIs. Follow for more.
More from me: 10 Dev Tools I Use Daily | 77 Scrapers on a Schedule | 150+ Free APIs
Top comments (0)