Full name: Path library: the Python standard-library module for object-oriented filesystem paths.
Definition
pathlib is the module of the Python §12.23 standard library that represents filesystem paths as objects. A path is the name by which a program reaches a file, such as /srv/safe/data/x.csv. The module has two layers. Pure path classes (PurePath and its subclasses) only split, join and compare names as text and never consult the disk. The concrete class Path adds methods that ask the operating system about the named file, open it or change it. The module’s name joins the words path and library.
The idea
A file server must hand out only files below the directory /srv/safe. It joins that directory and the name a client asked for, then checks that the result begins with /srv/safe. For the request ../secret/key the joined name is /srv/safe/../secret/key, which passes the check, yet the operating system opens /srv/secret/key. For link/passwd, where link is a symbolic link §13.10 (a small file whose content is another path) to /etc, the check passes again and /etc/passwd is opened. The text of a name and the file that the name reaches are different things.
The operating system does not open text. It performs path resolution §13.9: it starts at the root directory, or at the current directory for a relative name, looks up one component at a time in the directories as they exist at that moment, and continues through the content of every symbolic link it meets. pathlib draws the line between text and disk in its classes. Editing a name is like editing the address on an envelope: nobody checks that the street exists. Calling a concrete method is like sending a courier, who follows the roads as they are today, detours included. The picture stops at one point: a courier’s earlier trip says nothing about the route of a later trip, and a name checked earlier says nothing about the file a later call will reach.
How it works
Text only. These operations compute their result from the components of the name alone, so they give the same answer whatever is on the disk.
Joining with the operator
/or withjoinpath:Path("/srv/safe") / "a.txt"is/srv/safe/a.txt. A right-hand part that is itself absolute replaces everything to its left, soPath("/srv/safe") / "/etc/passwd"is/etc/passwd.Taking a name apart:
name,stem,suffix,parts,parent,parents.Rewriting and comparing:
with_name,with_suffix,relative_to,is_relative_to,is_absolute,matchand the comparison operators.Clean-up at construction: repeated slashes and single dots are removed and a trailing slash is dropped, so
a//b/./c/becomesa/b/c. A double dot..is kept, because removing it by text can change which file the name reaches. For the same reasonparentonly removes the last component: the parent offoo/..isfoo.
Follow symbolic links. These methods consult the file system when they are called and resolve the name afresh on every call: open, read_text, read_bytes, write_text, write_bytes, iterdir, stat, exists, is_file, is_dir, samefile, owner, group and chmod. Several accept follow_symlinks=False, which makes them report on a final symbolic link itself: stat and chmod since Python 3.10, exists since 3.12, and is_file, is_dir, owner and group since 3.13. The flag covers only the last component; links in the directories along the way are still followed. walk, added in Python 3.12, does not descend through links unless called with follow_symlinks=True.
Act on the link itself. lstat, is_symlink and readlink, which returns the path text stored in the link, look at a final symbolic link without following it. unlink removes the link, not its target, and rename and replace rename the link.
Resolve parents. absolute() only puts the current directory in front of a relative name; it neither removes .. nor follows links. resolve() is the only pathlib method that removes ... It queries the file system one component at a time, follows every symbolic link, and applies each .. to the directory actually reached, so the result is an absolute name that contains no link and no ... With the default strict=False, a part of the name that does not exist is appended without checking; with strict=True, a missing component raises FileNotFoundError. The older functions os.path.normpath and os.path.abspath, by contrast, remove .. by text alone.
Removing .. by text gives the wrong file whenever a symbolic link comes before it. If /srv/safe/link points to /etc, the name /srv/safe/link/../x reaches /etc, then its parent, the root directory, and then /x. os.path.normpath returns /srv/safe/x, a different file.
Worked example
Take a hypothetical file tree. The allowed root is /srv/safe. Inside it, data/x.csv is an ordinary file and link is a symbolic link to /etc. Outside it, the file /srv/secret/key exists. The server joins the root with each requested name into p and tests the result twice: by text with p.is_relative_to("/srv/safe"), and on the disk with p.resolve().is_relative_to("/srv/safe").
data/x.csv:pis/srv/safe/data/x.csv; the text test is true;resolve()returns the same name; the disk test is true. Accept.link/passwd:pis/srv/safe/link/passwd; the text test is true;resolve()follows the link and returns/etc/passwd; the disk test is false. Reject.../secret/key:pis/srv/safe/../secret/key, because pathlib keeps... Its first three components are/,srvandsafe, so the text test is true.resolve()returns/srv/secret/key; the disk test is false. Reject./etc/passwd: the absolute right-hand part replaces the root, sopis/etc/passwd; both tests are false. Reject.
Of the three hostile names, the text test stops one and lets two through; the disk test stops all three. These are the values that Python 3.12 on Linux returns for this tree.
The disk test is still a snapshot. Suppose a local user who may write in /srv/safe replaces the directory data by a symbolic link to /etc after the server has tested name 1 and before it opens the file. The server then opens /etc/x.csv, a file its test never saw. This is a time-of-check to time-of-use §9.26 (TOCTOU) race condition §9.2: the check and the use resolve the name separately, and the name changed in between. The repair is to make the check and the use one operation: open one component at a time relative to the directory already opened, refusing symbolic links with the flag O_NOFOLLOW (see descriptor-relative access §15.23), or, on Linux, open with the system call openat2 and its flag RESOLVE_BENEATH, which refuses any lookup that would leave the starting directory.
Stated precisely
Write a path as the sequence of its components . A pure operation is a function of these components only, so its result does not depend on the disk, the current directory or the time of the call. The method absolute() behaves in the same way, except that it also reads the current directory.
A concrete method performs path resolution at the moment it is called. Starting from the root for an absolute name, or from the current directory for a relative one, it looks up each component in the directory reached so far. If the entry found is a symbolic link, the lookup continues through the path stored in the link. For the last component only, a method called with follow_symlinks=False, and the methods lstat, is_symlink, readlink, unlink, rename and replace, act on the link instead. A component .. moves to the parent of the directory actually reached; after a link, that is the parent of the link’s target, not the directory that contains the link. No operation on text alone can therefore remove .. correctly.
p.resolve() returns an absolute path with no symbolic link and no .. that names the object the lookup reached during the call. That result names the same object later only under one assumption: no process changes any directory entry along the path in between. Two calls on the same Path object, even back to back, may reach different files. A Path object holds no reference to a file; it is a name. A program that must keep acting on one file keeps it open and uses the open file, which stays the same object whatever happens to its names.
Limits and common mistakes
Constructing a path creates nothing. Path("logs") / "sample.txt" is a name, and no file exists until a method such as touch or write_text creates one.
Testing and then using is a race. if p.exists(): p.open() can fail, or open a different file than the one tested; open directly and handle FileNotFoundError. exists() also returns false for some failed lookups, such as a loop of symbolic links, and since Python 3.14 for every operating-system error, missing permission included; false does not prove that the name is free.
is_relative_to and relative_to compare text. They report /srv/safe/../x as lying inside /srv/safe.
An absolute path is not a contained path. A resolved path inside the root can also name a file that exists elsewhere: a hard link, a second directory entry for the same file, is not a symbolic link, so resolve() does not reveal it.
Letter case: PureWindowsPath compares names without regard to case and PurePosixPath with regard to case. The default file systems of Windows and of Apple’s macOS ignore case, so on macOS /srv/SAFE and /srv/safe can be one directory, while PurePosixPath calls the two names different.
The trailing slash dropped at construction carries meaning for the operating system: name/ requires name to be a directory.
pathlib performs no authorization §1.7. Whether a call succeeds depends on the permissions of the operating-system user that runs the program; running the program with least privilege §1.15 limits the harm of a wrong check. The same containment problem for names stored inside archives is the subject of the archive path traversal §15.18 entry.
Questions answered
Which methods follow symlinks, resolve parents, or merely manipulate text?
In Python’s pathlib, the methods of the pure layer only manipulate text, the concrete methods that open or inspect a file follow symbolic links (small files that store another path) by default, and resolve() is the only method that resolves .. (parent) components. In detail:
Text only: joining with
/,name,suffix,parent,parents,parts,with_name,with_suffix,relative_to,is_relative_to,match, andabsolute(), which adds only the current directory.parentandis_relative_totreat..as an ordinary name.Follow symbolic links:
open,read_text,read_bytes,write_text,iterdir,stat,exists,is_file,is_dir,samefile,owner,chmod. Several of them acceptfollow_symlinks=False, added between Python 3.10 and 3.13 depending on the method, which stops at a final link; links earlier in the path are always followed.Act on the link itself:
lstat,is_symlink,readlink,unlink,rename.Resolve parents:
resolve()follows every link and applies each..to the directory actually reached. The functionsos.path.normpathandos.path.abspathremove..by text, which reaches a different file when a symbolic link precedes the...
Every method that touches the disk resolves the name again when it is called, so a result of resolve() or exists() describes that moment only.
Related entries: File descriptor versus pathname (§15.21), O_NOFOLLOW and descriptor-relative access (§15.23), Time-of-check to time-of-use (TOCTOU) (§9.26), Namespace and symlink resolution (§13.9), Hard link versus symbolic link (§13.10), Archive path traversal (§15.18). Further reading: [50, 117].