Handy one-liners for file I/O, data wrangling, quick HTTP servers, and more.
python -m http.server 8000
echo '{"name":"zing","version":1}' | python -m json.tool
python -m timeit -n 1000 '"-".join(str(i) for i in range(100))'
import pdb; pdb.set_trace() # Python 3.6 and earlier
breakpoint() # Python 3.7+
pip freeze > requirements.txt
pip install -r requirements.txt
lines = open("data.txt").read().splitlines()
open("out.txt", "w").write("\n".join(lines))
import csv
rows = list(csv.DictReader(open("data.csv")))
from pathlib import Path
text = Path("config.json").read_text(encoding="utf-8")
Path("output.json").write_text(text, encoding="utf-8")
from pathlib import Path
py_files = list(Path(".").rglob("*.py")) # recursive
logs = list(Path("logs").glob("*.log")) # single directory
flat = [x for sub in nested for x in sub]
inv = {v: k for k, v in original.items()}
from collections import Counter
freq = Counter(words)
freq.most_common(10) # top 10 items
from collections import defaultdict
grouped = defaultdict(list)
for item in items:
grouped[item["category"]].append(item)
from itertools import chain
combined = list(chain(list_a, list_b, list_c))
for i, val in enumerate(items, start=1):
print(f"{i}. {val}")
import re
emails = re.findall(r"[\w.+-]+@[\w-]+\.[\w.-]+", text)
import re
clean = re.sub(r"\s+", " ", text).strip()
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%'
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'
import textwrap
wrapped = textwrap.fill(long_string, width=72)
short = textwrap.shorten(long_string, width=40, placeholder="...")
import sys
script, first_arg, *rest = sys.argv
import os
for root, dirs, files in os.walk("/path/to/dir"):
for f in files:
print(os.path.join(root, f))
import subprocess
result = subprocess.run(["ls", "-la"], capture_output=True, text=True)
print(result.stdout)
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()
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
import tempfile
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
f.write('{"key": "value"}')
print(f.name)