7. Files & APIs
Read and write files safely, work with paths, and call web APIs reliably.
Q1 What is the best way to read from a file?
Answer: The with open(...) statement is the standard. It automatically handles closing the file, even if errors occur. The pathlib module is a modern, object-oriented way to handle file paths.
from pathlib import Path
path = Path("data.txt")
# write
path.write_text("Hello", encoding="utf-8")
# read
with path.open("r", encoding="utf-8") as f:
data = f.read()
Q2 How do you make an HTTP request to a web API?
Answer: The requests library is the standard for making HTTP requests. You can use it to GET data from or POST data to web services.
import requests
response = requests.get("https://api.github.com/users/python")
if response.status_code == 200:
data = response.json() # .json() parses the JSON response
Q3 What is JSON and how do you use it in Python?
Answer: JSON is a lightweight text format for data exchange, common in web APIs. Python's built-in json module can parse JSON strings into Python dictionaries (json.loads()) and convert Python objects into JSON strings (json.dumps()).
import json
data = json.loads('{"name": "Ada", "age": 30}')
text = json.dumps(data, indent=2, ensure_ascii=False)
Q4 How do you build a simple CLI with argparse?
Answer: Use argparse.ArgumentParser to define arguments and parse them from the command line.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
parser.add_argument("--times", type=int, default=1)
args = parser.parse_args(["Ada", "--times", "2"]) # example
for _ in range(args.times):
print(f"Hello {args.name}")
Q5 How do you work with CSV files?
Answer: Use the csv module for robust parsing and writing; always open files with newline="" on Windows to avoid extra blank lines.
import csv
from pathlib import Path
with Path("data.csv").open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["name", "age"])
writer.writerows([["Ada", 30], ["Bob", 25]])
with Path("data.csv").open("r", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
rows = list(reader)
Q6 How to read/write binary files?
Answer: Use modes "rb" and "wb"; process bytes objects.
data = Path("image.png").read_bytes()
Path("copy.png").write_bytes(data)
Q7 How to make HTTP requests robustly?
Answer: Always set timeouts, handle exceptions, and consider retries/backoff.
import requests
try:
resp = requests.get("https://example.com", timeout=5)
resp.raise_for_status()
except requests.exceptions.RequestException as e:
print("Request failed:", e)
Q8 How do you work with paths using pathlib?
Answer: Use Path methods like joinpath, glob, and iterdir for cross-platform path handling.
from pathlib import Path
logs_dir = Path("logs")
for p in logs_dir.glob("*.log"):
print(p.name)