Python One-Liners You’ll Use Weekly
Developers often underestimate how much Python can do in one line. From parsing JSON and iterating files to hitting APIs and transforming data — here’s a pack of 50 one-liners you’ll actually reuse every week.
Filesystem ops • Text & CSV
open('log.txt').read() # read file
open('data.txt', 'w').write('hello\n') # write text
sum(1 for _ in open('file.txt')) # count lines
[x.strip() for x in open('file.txt')] # list lines
import os; [f for f in os.listdir('.') if f.endswith('.py')] # list .py files
import glob; files = glob.glob('**/*.csv', recursive=True)
CSV & text in one go:
import csv; rows = list(csv.DictReader(open('data.csv')))
JSON / YAML
import json; data = json.load(open('data.json')) # read JSON
json.dump(data, open('out.json','w'), indent=2) # write JSON
import yaml; yaml.safe_load(open('conf.yaml')) # YAML to dict
Convert between formats:
json.dump(yaml.safe_load(open('conf.yaml')), open('conf.json','w'))
HTTP (requests)
import requests; data = requests.get('https://api.github.com').json()
r = requests.post('https://api.example.com', json={'ok':1}).json()
Quick file download:
import requests; open('img.jpg','wb').write(requests.get(url).content)
CLI (argparse)
import argparse; p=argparse.ArgumentParser(); p.add_argument('--n'); print(p.parse_args().n)
Small data tricks (itertools)
from itertools import groupby, combinations
list(combinations([1,2,3,4], 2)) # pairs
{k: len(list(g)) for k,g in groupby('aaabbccc')} # run-length encode
When to prefer one-liner vs function?
Use one-liners for scripts, data cleaning, or ad-hoc debugging. For anything reused — wrap it in a function with clear names and error handling.
Cross-platform file paths?
Always use pathlib.Path:
from pathlib import Path; Path.home() / 'Downloads'
Virtualenv / uv / poetry quickstart?
python -m venv .venv && source .venv/bin/activate
pip install requests
# or
uv venv && uv add requests
💡 See also: Regex Cheat Sheet
Save this post — it’s the perfect reference when you need just one line of Python magic.