Python — File I/O and Exceptions
File I/O with pathlib
pathlib.Path is the modern way to work with files. It handles cross-platform paths and provides clean read_text() / write_text() methods.
Reading a file
from pathlib import Path
path = Path('siddhartha.txt')
contents = path.read_text() # entire file as one string
lines = contents.splitlines() # split into a list of lines
for line in lines:
print(line)Writing to a file
path = Path('journal.txt')
msg = "I love programming."
path.write_text(msg) # creates file if missing; overwrites if presentpathlib vs open()
The older style uses
open()/f.read()/context managers.pathlibis the modern approach — simpler for basic read/write and handles OS path separators automatically. The cheat sheet uses pathlib exclusively.
Exceptions
Exceptions let you respond to errors gracefully rather than crashing. Structure:
try:
[code that might raise an exception]
except SomeSpecificError:
[what to do if that error occurs]
else:
[runs only if NO exception was raised in try]
Catching a ValueError
prompt = "How many tickets do you need? "
num_tickets = input(prompt)
try:
num_tickets = int(num_tickets) # raises ValueError if not numeric
except ValueError:
print("Please try again.")
else:
print("Your tickets are printing.")Catch specific exceptions
Always name the specific exception (e.g.,
ValueError,FileNotFoundError) rather than a bareexcept:. Bareexcept:silently swallows unexpected bugs.
Cross-References
- PythonControlFlow — try/except is a branching control structure
- PythonVariablesStringsInput — exceptions most often arise when converting
input()output - CppIOStreams — contrast: C++ uses streams (
cin/fstream) rather than path objects
graph TD A[File I/O] --> B["Path('filename.txt')"] B --> C["path.read_text() → string"] B --> D["path.write_text(msg)"] C --> E["contents.splitlines() → list of lines"] F[Exceptions] --> G["try: risky code"] G --> H["except ValueError: handle error"] G --> I["else: runs if no exception raised"]