Problems with the file system are almost never in the code but in the environment: the file is not there, the folder already exists, there are no permissions, the program is run from somewhere else… A robust program anticipates this.
import tempfile
from pathlib import Path
# Paths relative to the script itself, not to the folder it is run from:
# BASE = Path(__file__).resolve().parent
# DATA = BASE / "data" / "config.json"
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
target = base / "output" / "report.txt"
target.parent.mkdir(parents=True, exist_ok=True) # make sure the folder exists
target.write_text("done\n", encoding="utf-8")
print(target.read_text(encoding="utf-8").strip()) # done
try:
target.parent.mkdir() # already exists
except FileExistsError:
print("already existed") # already existed
try:
(base / "missing.txt").read_text()
except FileNotFoundError:
print("not found") # not found
(base / "missing.txt").unlink(missing_ok=True) # does not fail if it does not exist
root = base.resolve()
dangerous = (root / ".." / "outside.txt").resolve()
print(dangerous.is_relative_to(root)) # False it escapes the allowed folder!
- Errors have their own names:
FileNotFoundError,FileExistsError,PermissionError,IsADirectoryError,NotADirectoryError. All of them inherit fromOSError. - It is better to try and catch (
try/except) than to check first withexists(): between the check and the use another process may have changed the file. - Relative paths depend on the working folder; if your program has to find its own data, use
Path(__file__).resolve().parent. - Never build paths from what the user types without validating: a name such as
../../etc/passwdescapes the intended folder. Resolve the path and check withis_relative_to. - For use-once-and-discard files,
tempfile.TemporaryDirectory()andNamedTemporaryFile()create and clean up for you.
When you work with the web corrector, each run starts in its own folder that contains only the files of the test, and it is discarded at the end. That is why in this lesson’s exercises you use relative paths such as Path(".") or "data".