Lesson · File I/O & Filesystem
Filesystem Operations
55 min readFilesystem Operations
Filesystem work involves more than opening files: programs create directories, move data, inspect metadata, and use temporary locations. High-level `shutil` and `tempfile` tools reduce platform-specific mistakes.
Learning goals
- Create and remove directories with
mkdirandrmdirand say when onlyshutil.rmtreecan clear a tree. - Choose between
shutil.copy,copy2, andmovebased on whether metadata must travel and whether the source should stay. - Explain why
TemporaryDirectorydeletes its contents even when the block body raises. - Read size, modification time, and mode from
Path.stat()and name the units. - Tell
osprimitives apart fromshutilwrappers and pick the higher layer when it exists.
Mental model
Filesystem operations split into two layers: os exposes thin, platform-specific primitives (working directory, permissions, os.path string helpers), and shutil plus tempfile wrap whole-file and whole-tree operations with sensible defaults. Everyday code should call the higher layer and drop to os only when there is no equivalent, which keeps platform differences in one place.
Core idea
Most filesystem bugs are lifecycle bugs: a directory created but never cleaned up, a copy that silently dropped metadata, a temp file that outlived its use. The high-level tools encode the correct lifecycle instead of making you rebuild it: TemporaryDirectory couples creation to a with block, copy2 carries timestamps that plain copy drops, and move picks between rename and copy-then-delete for you.
os
The os module is the standard library's low-level interface to the operating system: process environment, working directory, file descriptors, permissions, and the os.path string helpers all live there. Its functions map closely to system calls, so errors arrive as specific OSError subclasses and platform differences stay visible rather than hidden.
shutil
shutil provides the high-level operations that os leaves to you: copy, copy2, copytree, move, rmtree, make_archive, and disk usage checks. It works on paths and whole trees rather than descriptors, applies sensible defaults, and preserves metadata only where the function's promise says so.
Create/remove directories
Path.mkdir, like os.mkdir, creates a single directory, raising FileExistsError if it already exists and FileNotFoundError if a parent is missing, while parents=True and exist_ok=True opt into the forgiving variants. Removal is stricter: rmdir deletes only empty directories and raises OSError otherwise, so a populated tree needs shutil.rmtree, which deletes everything below the path without a prompt.
Copy/move files
shutil.copy(source, target) copies content and permission bits but not timestamps, copy2 also carries modification and access times, and move renames when both sides are on the same filesystem or falls back to copy-then-delete. copy and copy2 raise SameFileError when source and target are the same file, which stops the copy from destroying its own source.
Environment variables
Environment variables cross the process boundary as strings. Convert and validate them immediately, and avoid treating their mere presence as proof of safe or well-formed configuration.
Temporary files
Temporary-file APIs create names and files with safer uniqueness and cleanup behavior than ad-hoc random filenames. Treat lifetime and visibility requirements explicitly.
Metadata
File metadata arrives through Path.stat() as an os.stat_result: st_size is the size in bytes, st_mtime is a modification timestamp in seconds since the epoch, and st_mode packs the file type together with permission bits. The stat module helps interpret those values: stat.filemode renders a readable string such as -rw-r--r--, and stat.S_ISDIR answers type questions.
Walkthrough
TemporaryDirectory()creates a uniquely named directory and binds it totemp; when thewithblock ends, the directory and everything inside it are deleted, even if the body raises.source.write_text("data", encoding="utf-8")createssource.txtinside that directory in one call, soroot,source, andtargetall live under the temporary root.shutil.copy2(source, target)copies the bytes and the timestamps tocopy.txt, andtarget.read_text(...)opens the copy fresh and returns the string"data", whichprintshows.- Predict before running: the printed line, then which exception a second
target.read_text()raises after thewithblock has exited.
Experiments to try
- Print
source.stat().st_sizeafter writing and check it equalslen("data"); then compare the copy's size. - Swap
shutil.copy2forshutil.copyand comparest_mtimeon source and target; record which one changes. - Replace the
Pathjoin withos.path.joinand diff readability; keep the version you would review faster. - Move a file with
shutil.moveand then read the old name; capture the exact exception to confirm the source is gone.
Common mistakes
- Expecting
os.renameto work across filesystems: it raisesOSErrorwhen source and destination live on different drives, whileshutil.movehandles the copy-plus-delete fallback. - Calling
rmdiron a directory that still has files: it refuses withOSError(the message mentions the directory is not empty) by design; clearing a tree requiresshutil.rmtree. - Creating temporary names from plain random strings: collisions and leftovers follow because nothing ties the name to a lifecycle;
TemporaryDirectoryandNamedTemporaryFilecreate unique names and clean them up. - Assuming a copy preserves everything:
shutil.copykeeps content and permission bits but not timestamps, so builds that compare modification times see a brand-new file at the destination.
Practice: Easy
- In a
TemporaryDirectoryblock, create a nested directory withmkdir(parents=True), then remove the leaf withrmdirand list what still exists. - Write
source.txt, copy it withshutil.copy2tocopy.txt, and assert bothread_textcalls return the same string. - Print
source.stat().st_sizeandsource.stat().st_mtimeand identify the units of each value.
Practice: Medium
- Write
backup(source, folder)that copies a file into a folder, creating the folder if missing; test it twice on the same source and decide whether overwriting is correct. - Copy a directory tree with
shutil.copytree, then modify a file in the copy and verify the original is unchanged; record whatcopytreeraises when the destination already exists. - Refactor a script that builds paths with
os.path.joinand deletes withos.removeinto one that usesPathand aTemporaryDirectory; note what cleanup you no longer write yourself.
Practice: Hard
- Build
rotate_logs(folder, keep)that keeps the newestkeepfiles and deletes the rest; define the ordering key fromstat().st_mtimeand test it with files created in a known order. - Design a two-directory sync step: copy new files with
copy2, move renamed ones, and delete stale targets; list the failure modes when the trees are on different drives and none of the operations are atomic together. - Create a file, read
st_mode, and explain the bits that mark it as a regular file and as readable; then change permissions withos.chmodand confirm the change throughstat.filemode.
Lesson checklist
- I can choose between
Path.mkdirflags andshutil.rmtreefor creating and clearing directories. - I can say which metadata
copy,copy2, andmovecarry across. - I can explain why a
TemporaryDirectoryblock deletes its contents even after an exception. - I can read
st_size,st_mtime, andst_modeoff astat()result and name their units.
Remember
Filesystem work succeeds when creation, use, and cleanup are tied together: `TemporaryDirectory` binds all three in one `with` block, and the `shutil` functions choose the correct low-level sequence (rename or copy plus delete, metadata included or not) so you do not reassemble it. Reach for `os` when you need a primitive that `shutil` does not wrap, and expect the specific `OSError` subclasses those primitives raise.
Interview angles
What is the main purpose of **os**?+
The os module is the low-level interface to the operating system: environment, working directory, permissions, and os.path helpers. Its functions mirror system calls, so errors are specific OSError subclasses and platform differences stay visible.
What should you pay attention to when using **shutil**?+
shutil wraps whole-file and whole-tree operations with sensible defaults: copy2 carries timestamps that copy drops, move falls back to copy-then-delete across filesystems, and rmtree deletes recursively. Check which metadata each function promises before relying on it.
How does **Create/remove directories** fit into this lesson?+
mkdir creates a single directory, so it needs parents=True for missing intermediates and exist_ok=True to tolerate repeats; rmdir removes only empty directories, so clearing a populated tree requires shutil.rmtree, which has no undo.
What does `shutil.copy` do differently from `copy2`, and when does the difference matter?+
copy copies content and permission bits; copy2 also copies modification and access times. The difference matters when later code compares timestamps, such as backup or build tools deciding whether a file is current.