A Path is not a string¶
Level: 201 · for Python programmers
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The bullets below are the questions the finished page has to answer.
One line: pathlib.Path is an object with / for joining and methods that touch the disk, not a str with extra methods — so path + '.bak' is a TypeError, Path('a') / 'b' is the join, str(p) is the way to a string and os.fspath() the polite one, p.suffix is the last dot only, and Path('..').resolve() asks the filesystem while Path('a/../b') never does.
What the finished page has to answer¶
- Pure paths against concrete ones: which methods are string arithmetic,
parent,name,stem,suffix,with_suffix, and which touch the disk,exists,resolve,glob,read_text. suffixonarchive.tar.gz, andsuffixes.resolve()follows symlinks andabsolute()does not, and whya/../bis notbon a filesystem with links; the example has to build its own tree undertempfileand print relative paths only, because an absolute path is never the same on two machines.read_text()withoutencoding=makes the same bet Opening a file describes.glob()returns a generator, so it is used up after one loop.- Where a
Pathis accepted: anything that callsos.fspath(), which isopen, theosmodule andsubprocess, and where it is not: astrmethod,json.dumps, a+. PureWindowsPathfrom macOS, for reading a path that came from somewhere else, and the bytes path, which Filenames are not text owns.
See also¶
- Filenames are not text and Opening a file
pathlib↗ in the library reference- The Rust library's files chapter ↗, where a
Pathis not a string either, and not even valid UTF-8