How to read and write CSV files
Using the csv module with clear, copy-paste examples.
Step-by-step solutions for data handling, file operations, HTTP, databases, testing, and automation. Problem-focused and easy to reuse.
How-To guides are short, task-focused articles: you have a concrete goal (read a CSV, call an API, loop with an index) and you want working code and clear steps. Each guide assumes you know basic Python—Getting Started, data types, functions, and lists or dictionaries when relevant—and focuses on one problem at a time.
We cover files and data: read and write CSV, read and write JSON, read a text file, write to a text file, read YAML. HTTP and APIs: HTTP GET, HTTP POST, timeouts, retries. Databases: connect to SQLite, query SQLite safely. Lists and strings: loop with index (enumerate), sort a list, split a string, join strings. Environment and tooling: virtual environment, install with pip, environment variables. For data science workflows see CSV with Pandas, Matplotlib, and related guides.
Use the sidebar or the list below to jump to a guide. If you hit an error, check the Errors & Exceptions section (e.g. FileNotFoundError, KeyError) or the linked Basics and Concepts pages.
Using the csv module with clear, copy-paste examples.
Use json.load, json.dump, and avoid common pitfalls.
Use enumerate() when you need both the item and its index.
Use sorted() for a new list or list.sort() in place.
Use slicing s[::-1] or reversed() with ''.join().
Use key in d or d.get() for safe access.
Use ** unpacking, dict.update(), or | (Python 3.9+).
Open with open(path, 'r') and use read(), readline(), or loop.
Open with open(path, 'w') and use write() or writelines().
Use datetime.strptime() with a format string.
Use datetime.strftime() with format codes.
Use requests.get(url) and check response.status_code and response.text.
Use requests.post(url, json=...) or data=... for form data.
Use BeautifulSoup(html, 'html.parser') and .find() / .select().
Use sqlite3.connect('file.db') and a cursor to run queries.
Use parameterized queries with ? placeholders to avoid SQL injection.
Run python -m venv .venv, then activate with source .venv/bin/activate or .venv\Scripts\activate.
Run pip install <package>. Use pip install -r requirements.txt for a list.
Use os.environ['KEY'] or os.getenv('KEY', default).
Use subprocess.run() for simple cases. Capture output with capture_output=True.
Use a list comprehension, itertools.chain.from_iterable, or a recursive helper.
Use list(dict.fromkeys(lst)) to preserve order, or list(set(lst)) if order does not matter.
Use list.count(), collections.Counter, or a loop.
Use str.split() or str.splitlines(). Regex: re.split().
Use str.join(iterable). The separator is the string you call join on.
Use re.search() or re.match(). Compile with re.compile() for reuse.
Use re.sub(pattern, repl, string). Use a callable as repl for dynamic replacement.
Use os.makedirs(path) or Path.mkdir(). Use exist_ok=True to avoid errors if it exists.
Use os.listdir(), pathlib.Path.iterdir(), or glob.glob().
Use os.remove(path) or Path.unlink(). Check existence first if needed.
Use shutil.copy(src, dst) or shutil.copy2 to preserve metadata.
Use os.rename() or shutil.move(). Move works across filesystems.
Use pyyaml: yaml.safe_load(stream). Prefer safe_load over load.
Use yaml.dump(data, stream). Use default_flow_style=False for block style.
Use urllib.parse.urlparse() for components, or urlsplit / parse_qs for query strings.
Use base64.b64encode() and b64decode(). Work with bytes.
Use hashlib: hashlib.sha256(s.encode()).hexdigest(). Use SHA-256 or better for security.
Use secrets for security-sensitive randomness: secrets.token_hex(16) or token_urlsafe.
Use random.shuffle(lst) to shuffle in place. Use random.sample(lst, k) for a random sample.
Use round(x, n) for rounding to n decimals. Use math.floor / ceil for down/up.
Use f-strings f'{x:.2f}', format(), or locale for localized formatting.
Use int(s). Use int(s, 16) for hex. Handle ValueError for invalid strings.
Use d.get(key, default), try/except KeyError, or collections.defaultdict.
Use copy.deepcopy(x) for nested structures. list.copy() or lst[:] only copies the top level.
Use a list comprehension with slicing, or more_itertools.chunked. Example: [lst[i:i+n] for i in range(0,len(lst),n)].
Use zip(a, b) to get pairs. Use list(zip(...)) if you need a list.
Swap keys and values. Use {v: k for k, v in d.items()}. Watch out for duplicate values.
Use sorted(d.items(), key=lambda x: x[1]). Use dict() to get a dict back (Python 3.7+ order preserved).
Use list comprehension [x for x in lst if cond] or filter(func, lst).
Use list comprehension [f(x) for x in lst] or map(f, lst). list(map(...)) if you need a list.
Use list.index(x). Use enumerate or a loop if you need to handle duplicates or a predicate.
Use lst[i] = new_value. Use [new if x==old else x for x in lst] to replace all matches.
Use collections.defaultdict(factory). Missing keys get the default from factory().
Use collections.Counter(iterable) for frequency counts. most_common(n) returns top n.
Use json.loads(s) for a string. Use json.load(f) for a file.
Use json.dumps(obj, indent=2). Use json.dump(..., indent=2) when writing to a file.
Use a loop with try/except, or a library like tenacity or requests-retry.
Pass timeout=10 to requests.get() or post(). Use a tuple (connect, read) for finer control.
Use requests.get(url) and write response.content to a file. Use streaming for large files.
Use pd.read_csv('file.csv'). Use encoding, sep, and header as needed.
Use boolean indexing: df[df['col'] > 0]. Use query() for string expressions.
Use df.groupby('col') then .sum(), .mean(), .agg(), etc.
Use pd.read_excel('file.xlsx'). Install openpyxl for .xlsx. Use sheet_name to pick sheets.
Use df.to_excel('out.xlsx'). Use ExcelWriter for multiple sheets.
Use plt.plot(x, y), then plt.show(). Use plt.figure() and ax for more control.
Use plt.savefig('out.png'). Set dpi, bbox_inches='tight' as needed.
Create ArgumentParser(), add arguments with add_argument(), then parse_args().
Use sys.stdin (line by line: for line in sys.stdin) or input() for interactive prompts.
Use logging.basicConfig(filename='app.log') or add a FileHandler to a logger.
Use @dataclass and define attributes. Get __init__, __repr__ automatically.
Use class Color(Enum): RED = 1; GREEN = 2. Access with Color.RED.
Install pytest, name files test_*.py, define def test_*(). Run pytest.
Use unittest.mock.patch or pytest fixtures. Patch where the object is used, not where it is defined.
Use with expr as x:. Create one with @contextmanager or a class with __enter__ / __exit__.
Use yield instead of return in a function. Call it to get an iterator; iterate with for or next().
Define async def functions, use await. Run with asyncio.run(main()).
Use concurrent.futures.ThreadPoolExecutor. Submit tasks with executor.submit(fn, *args) or map.
Define a function that takes a callable and returns a callable. Use @decorator above the target.
Use functools.lru_cache for memoization. Use @lru_cache(maxsize=128) above the function.
Check type and value, use try/except for conversions. Use a library like pydantic for schemas.
Remove or replace unsafe characters. Use re.sub(r'[\/:*?"<>|]', '_', s) or a whitelist of allowed chars.
Use python-dotenv: load_dotenv() then os.getenv(). Call load_dotenv() early in the app.
Use configparser.ConfigParser(), read('config.ini'), then get(section, key).
Use zipfile.ZipFile('out.zip', 'w') and write(path) or writestr.
Use zipfile.ZipFile('file.zip', 'r') and extractall() or extract(member).
Use smtplib.SMTP or SMTP_SSL. Create a message with email.mime, then sendmail.
Use a regex pattern for basic checks. For robust validation, use a library like email-validator.
Use requests.Session() to reuse TCP connections and cookies across requests.
Use requests.Session() for automatic cookie handling. Access response.cookies or set cookies=....
Define def fixture_name() and pass it as an argument to tests. Use @pytest.fixture.
Use @pytest.mark.parametrize('arg', values) to run the same test with different inputs.
Use xml.etree.ElementTree: ET.parse('file.xml') or ET.fromstring(s), then find / findall.
Add annotations like def f(x: int) -> str:. Use list[int], dict[str, int], Optional, etc.
Use dict(zip(keys, values)) or {k: v for k, v in pairs}. Use dict.fromkeys(keys, default) for same value.
Use list(zip(*matrix)) for a list of tuples, or numpy.array(m).T for NumPy.
Use zip(lst, lst[1:]) or itertools.pairwise (Python 3.10+).
Use collections.deque for O(1) append/pop at both ends. appendleft, popleft, maxlen for bounded queues.
Use argparse for full control, or sys.argv for minimal parsing.
Assign sys.stdout to a file-like object, or use contextlib.redirect_stdout.
Pass headers={'User-Agent': '...', 'Authorization': 'Bearer ...'} to get() or post().