KKAIROS
Practical guideIllustrative3 min read

Python pathlib: join paths, read a file and list a folder

pathlib models paths as objects that can be joined, read and globbed. The run shows joining, reading and globbing.

Published:

Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.

TE-55-A: pathlib joins, reads and globs paths; conversion to str is still needed for plain-string APIs

Setup for this run, inside a throwaway directory (mktemp -d):

mkdir -p d; printf 'x\n' > d/a.txt; printf 'y\n' > d/b.md

Command:

python3 -c "from pathlib import Path; p=Path('d'); print((p/'a.txt').read_text().strip()); print(sorted(x.name for x in p.glob('*.txt'))); print(type(str(p/'a.txt')).__name__)"

Recorded output:

x
['a.txt']
str

TE-55-B: a Path gives its parts as attributes, and exists() answers True or False without raising

Setup for this run, inside a throwaway directory (mktemp -d):

mkdir -p d; printf 'x\n' > d/a.txt
cat > s.py <<'EOS'
from pathlib import Path
p = Path('d/a.txt')
print(p.suffix, p.stem, p.parent, p.exists(), Path('d/zz').exists())
EOS

Command:

python3 s.py

Recorded output:

.txt a d True False

Exit status: 0. The output matches the expected text written before the run.

TE-55-C: expected non-zero exit: read_text on a file that does not exist raises FileNotFoundError

Setup for this run, inside a throwaway directory (mktemp -d):

mkdir -p d
cat > s.py <<'EOS'
from pathlib import Path
print(Path('d/nosuch.txt').read_text())
EOS

The file ../err.txt sits one level above the working folder, inside the same throwaway tree. The output block below shows only the last line of the error; the full traceback went to ../err.txt.

Command:

python3 s.py 2>../err.txt; rc=$?; tail -n 1 ../err.txt; exit $rc

Recorded output:

FileNotFoundError: [Errno 2] No such file or directory: 'd/nosuch.txt'

Exit status: 1. This status and the output match what was written before the run.

Reading the recorded output

The first line, x, is the text of d/a.txt read through (p/'a.txt').read_text(), with strip removing the newline. The second line is the sorted names that p.glob('*.txt') found in the folder d: only ['a.txt']. By the setup, the folder also holds b.md, and the pattern did not match it. The third line shows that str(p/'a.txt') has the type str, a plain string. The run does not print the path text itself.

TE-55-B: for the path d/a.txt the suffix is .txt, the stem is a and the parent is d. exists() gave True for d/a.txt and False for d/zz, with no error for the missing path. TE-55-C: read_text on d/nosuch.txt stopped with FileNotFoundError: [Errno 2] No such file or directory: 'd/nosuch.txt', with exit status 1.

Ad

Limits

The run shows joining, read_text and glob on a small directory. Writing, permissions and path normalisation are not tested here.

Source

Evidence

Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-55-A | pathlib joins, reads and globs paths; conversion to str is still needed for plain-string APIs | 0 | PASS | 7418bf5b8210 | | TE-55-B | a Path gives its parts as attributes, and exists() answers True or False without raising | 0 | PASS | 597dfd350a1e | | TE-55-C | expected non-zero exit: read_text on a file that does not exist raises FileNotFoundError | 1 | PASS | d59779702900 |

Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.

All full guides: All guides