PythonMastery
Short answers

How do I… in Python?

26 questions people type into a search box, each answered on one page: the code first, then the one or two things that trip people up. Press Run and the example works, here in your browser. Every output on these pages is checked when the site is built.

Files and data

CSV, JSON, text files, folders and SQLite.
How do I read a CSV file in Python?Open the file with newline='' and hand it to csv.DictReader: each row arrives as a dictionary keyed by the header. Every value is a string until you convert it.How do I write a CSV file in Python?Open the file with newline='' and use csv.DictWriter: writeheader() once, then writerows(). The csv module quotes commas and line breaks inside values for you.How do I read a JSON file in Python?json.load(f) reads a file, json.loads(text) parses a string. Objects become dicts, arrays become lists, and bad JSON raises JSONDecodeError with the line.How do I write a dictionary to a JSON file in Python?json.dump(data, f, indent=2) writes a readable file. ensure_ascii=False keeps accented names readable; default=str handles dates and other types JSON can't.How do I read a file line by line in Python?Loop over the open file: for line in f. It reads one line at a time, so a 10 GB log costs the same memory as a 10-line one. Strip the newline with rstrip().How do I check if a file exists in Python?Path('notes.txt').exists() answers it. About to open the file anyway? Skip the check and catch FileNotFoundError: the file can vanish in between.How do I list all files in a folder in Python?Path('folder').glob('*.csv') lists what matches, iterdir() lists everything, rglob() goes into subfolders. Sort the result: the order isn't guaranteed.How do I use SQLite in Python?sqlite3 ships with Python: connect to a file, run SQL, and always pass values with ? placeholders, never f-strings. A with block commits your writes.

Lists and dictionaries

Sorting, merging, de-duplicating, flattening.

Strings and numbers

Converting, searching, splitting, reversing.

Dates and time

Today's date, parsing dates, the gap between two.

The web and your computer

APIs, downloads, shell commands, environment variables.
want the long version?The How-to track

These pages answer one question each. The How-to track covers the same ground properly — scraping, APIs, databases, CSV and JSON, testing, logging — when you have twenty minutes instead of two.