Skip to content

Commit c146ad3

Browse files
author
Floris Lambrechts
committed
bpo-39090: Doc: Add a chapter on making paths absolute
Discussing Path.resolve(), os.path.abspath() and Path.cwd() / 'otherpath' in that order, to emphasize that resolve() is the preferred way.
1 parent 8c579b1 commit c146ad3

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

‎Doc/library/pathlib.rst‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1136,6 +1136,55 @@ call fails (for example because the path doesn't exist).
11361136
have the same meaning as in :func:`open`.
11371137

11381138
.. versionadded:: 3.5
1139+
1140+
1141+
.. _absolute-paths:
1142+
1143+
Absolute paths
1144+
--------------
1145+
1146+
A path is considered *absolute* (:func:`PurePath.is_absolute`) if it has
1147+
a *root*.
1148+
1149+
But there are *multiple* details which may change when transforming
1150+
a path into its full, canonical variant.
1151+
1152+
- Add ``root`` (local or global) if it's not already present.
1153+
- Add ``drive`` letter or name if the Path flavour allows it and it's not
1154+
already present.
1155+
- Replace releative parts ("``..``") with absolute ones.
1156+
- Replace symbolic links or junctions with their destination.
1157+
- Change case to the canonical case on case-insensitive but case-preserving
1158+
file systems.
1159+
- Replace ``drive`` with the UNC share name if the drive is a Windows mapped
1160+
network share ("``X:``" becomes "``\\filehost\folder``")
1161+
1162+
The function :meth:`Path.resolve` applies all of the above
1163+
transformations.
1164+
1165+
If the path is not yet absolute, it adds ``root``, ``drive`` and the base
1166+
folder path of the current working directory as retrieved by
1167+
:func:`Path.cwd`.
1168+
1169+
In contrast, :func:`os.path.abspath` also uses the current working directory
1170+
but it does *not* follow symbolic links, never modifies case, and does not
1171+
replace network share ``drive`` with the UNC path.
1172+
1173+
It also behaves non-*strict*: :func:`os.path.abspath` never raises
1174+
:exc:`FileNotFoundError` -- no matter which Python version is used.
1175+
1176+
If you desire even less side effects and only want to ensure the path
1177+
has a ``root``, then simply prepend it with the current working
1178+
directory::
1179+
1180+
>>> Path.cwd() / '../file.txt'
1181+
PosixPath('/home/anne/../file.txt')
1182+
1183+
This technique preserves the path if it was already absolute:
1184+
1185+
>>> Path.cwd() / "/absolute/path"
1186+
PosixPath('/absolute/path')
1187+
11391188

11401189
Correspondence to tools in the :mod:`os` module
11411190
-----------------------------------------------

0 commit comments

Comments
 (0)