Python One-Liners

Handy one-liners for file I/O, data wrangling, quick HTTP servers, and more.

Quick Servers & Tools

Spin up an HTTP server in the current directory

python -m http.server 8000

Pretty-print JSON from the command line

echo '{"name":"zing","version":1}' | python -m json.tool

Benchmark a snippet with timeit

python -m timeit -n 1000 '"-".join(str(i) for i in range(100))'

Drop into the debugger at a specific line

import pdb; pdb.set_trace()   # Python 3.6 and earlier
breakpoint()                   # Python 3.7+

Dump installed packages to requirements.txt

pip freeze > requirements.txt

Install from requirements in one shot

pip install -r requirements.txt

File I/O

Read a file into a list of lines

lines = open("data.txt").read().splitlines()

Write a list of strings to a file

open("out.txt", "w").write("\n".join(lines))

Read a CSV into a list of dicts

import csv
rows = list(csv.DictReader(open("data.csv")))

Use pathlib for clean path handling

from pathlib import Path
text = Path("config.json").read_text(encoding="utf-8")
Path("output.json").write_text(text, encoding="utf-8")

Find files with glob patterns

from pathlib import Path
py_files = list(Path(".").rglob("*.py"))        # recursive
logs     = list(Path("logs").glob("*.log"))      # single directory

Data Wrangling

Flatten a list of lists

flat = [x for sub in nested for x in sub]

Invert a dictionary

inv = {v: k for k, v in original.items()}

Count occurrences with Counter

from collections import Counter
freq = Counter(words)
freq.most_common(10)          # top 10 items

Group items with defaultdict

from collections import defaultdict
grouped = defaultdict(list)
for item in items:
    grouped[item["category"]].append(item)

Chain multiple iterables together

from itertools import chain
combined = list(chain(list_a, list_b, list_c))

Enumerate with a custom start index

for i, val in enumerate(items, start=1):
    print(f"{i}. {val}")

String & Regex

Extract all emails from a string

import re
emails = re.findall(r"[\w.+-]+@[\w-]+\.[\w.-]+", text)

Replace multiple whitespace with a single space

import re
clean = re.sub(r"\s+", " ", text).strip()

F-string formatting tricks

n = 1234567.89
f"{n:,.2f}"          # '1,234,567.89'
f"{n:.0f}"           # '1234568'
f"{'hello':>20}"     # right-align in 20 chars
f"{'hello':_^20}"    # center with _ fill
f"{0.856:.1%}"       # '85.6%'

Split and rejoin patterns

csv_line = "a, b , c,d"
vals = [v.strip() for v in csv_line.split(",")]   # ['a','b','c','d']
back = " | ".join(vals)                            # 'a | b | c | d'

Wrap long text to a fixed width

import textwrap
wrapped = textwrap.fill(long_string, width=72)
short   = textwrap.shorten(long_string, width=40, placeholder="...")

System & CLI

Quick access to CLI arguments

import sys
script, first_arg, *rest = sys.argv

Walk a directory tree

import os
for root, dirs, files in os.walk("/path/to/dir"):
    for f in files:
        print(os.path.join(root, f))

Run a shell command and capture output

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

Minimal argparse setup

import argparse
parser = argparse.ArgumentParser(description="My tool")
parser.add_argument("input", help="Input file path")
parser.add_argument("-o", "--output", default="out.txt")
parser.add_argument("-v", "--verbose", action="store_true")
args = parser.parse_args()

Copy, move, and remove files with shutil

import shutil
shutil.copy2("src.txt", "dst.txt")          # copy with metadata
shutil.move("old.txt", "archive/old.txt")   # move / rename
shutil.rmtree("temp_dir")                   # delete directory tree

Create a temporary file or directory

import tempfile
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
    f.write('{"key": "value"}')
    print(f.name)