• Home
  • Raw
  • Download

Lines Matching +full:path +full:- +full:is +full:- +full:absolute

2 :mod:`pathlib` --- Object-oriented filesystem paths
6 :synopsis: Object-oriented filesystem paths
12 .. index:: single: path; operations
14 --------------
17 appropriate for different operating systems. Path classes are divided
18 between :ref:`pure paths <pure-paths>`, which provide purely computational
19 operations without I/O, and :ref:`concrete paths <concrete-paths>`, which
22 .. image:: pathlib-inheritance.png
24 :class: invert-in-dark-mode
26 If you've never used this module before or just aren't sure which class is
27 right for your task, :class:`Path` is most likely what you need. It instantiates
28 a :ref:`concrete path <concrete-paths>` for the platform the code is running on.
37 useful since those simply don't have any OS-accessing operations.
40 :pep:`428`: The pathlib module -- object-oriented filesystem paths.
43 For low-level path manipulation on strings, you can also use the
44 :mod:`os.path` module.
48 ---------
52 >>> from pathlib import Path
56 >>> p = Path('.')
70 >>> p = Path('/etc')
77 Querying path properties::
91 .. _pure-paths:
94 ----------
96 Pure path objects provide path-handling operations which don't actually
102 A generic class that represents the system's path flavour (instantiating
109 path segment, an object implementing the :class:`os.PathLike` interface
110 which returns a string, or another path object::
112 >>> PurePath('foo', 'some/path', 'bar')
113 PurePosixPath('foo/some/path/bar')
114 >>> PurePath(Path('foo'), Path('bar'))
117 When *pathsegments* is empty, the current directory is assumed::
122 If a segment is an absolute path, all previous segments are ignored
123 (like :func:`os.path.join`)::
130 On Windows, the drive is not reset when a rooted relative path
131 segment (e.g., ``r'\foo'``) is encountered::
138 meaning of a path for various reasons (e.g. symbolic links, UNC paths)::
150 to ``PurePosixPath('bar')``, which is wrong if ``foo`` is a symbolic link
153 Pure path objects implement the :class:`os.PathLike` interface, allowing them
154 to be used anywhere the interface is accepted.
161 A subclass of :class:`PurePath`, this path flavour represents non-Windows
167 *pathsegments* is specified similarly to :class:`PurePath`.
171 A subclass of :class:`PurePath`, this path flavour represents Windows
179 *pathsegments* is specified similarly to :class:`PurePath`.
191 and orderable. These properties respect the flavour's case-folding
216 The slash operator helps create child paths, like :func:`os.path.join`.
217 If the argument is an absolute path, the previous path is ignored.
218 On Windows, the drive is not reset when the argument is a rooted
219 relative path (e.g., ``r'\foo'``)::
234 A path object can be used anywhere an object implementing :class:`os.PathLike`
235 is accepted::
242 The string representation of a path is the raw filesystem path itself
244 pass to any function taking a file path as a string::
253 Similarly, calling :class:`bytes` on a path gives the raw filesystem path as a
260 Calling :class:`bytes` is only recommended under Unix. Under Windows,
261 the unicode form is the canonical representation of filesystem paths.
267 To access the individual "parts" (components) of a path, use the following
272 A tuple giving access to the path's various components::
326 If the path starts with more than two successive slashes,
343 an implementation-defined manner, although more than two leading slashes
363 the path::
378 The logical parent of the path::
384 You cannot go past an anchor, or empty path::
394 This is a purely lexical operation, hence the following behaviour::
400 If you want to walk an arbitrary filesystem path upwards, it is
401 recommended to first call :meth:`Path.resolve` so as to resolve
407 A string representing the final path component, excluding the drive and
435 A list of the path's file extensions::
447 The final path component, without its suffix::
459 Return a string representation of the path with forward slashes (``/``)::
470 Represent the path as a ``file`` URI. :exc:`ValueError` is raised if
471 the path isn't absolute.
483 Return whether the path is absolute or not. A path is considered absolute
503 Return whether or not this path is relative to the *other* path.
516 With :class:`PureWindowsPath`, return ``True`` if the path is considered
518 ``False`` is always returned.
531 Calling this method is equivalent to combining the path with each of
546 Match this path against the provided glob-style pattern. Return ``True``
547 if matching is successful, ``False`` otherwise.
549 If *pattern* is relative, the path can be either relative or absolute,
550 and matching is done from the right::
559 If *pattern* is absolute, the path must be absolute, and the whole path
567 As with other methods, case-sensitivity follows platform defaults::
577 Compute a version of this path relative to the path represented by
578 *other*. If it's impossible, ValueError is raised::
590 …ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other ab…
592 …NOTE: This function is part of :class:`PurePath` and works with strings. It does not check or acce…
597 Return a new path with the :attr:`name` changed. If the original path
598 doesn't have a name, ValueError is raised::
614 Return a new path with the :attr:`stem` changed. If the original path
615 doesn't have a name, ValueError is raised::
638 Return a new path with the :attr:`suffix` changed. If the original path
639 doesn't have a suffix, the new *suffix* is appended instead. If the
640 *suffix* is an empty string, the original suffix is removed::
653 .. _concrete-paths:
657 --------------
659 Concrete paths are subclasses of the pure path classes. In addition to
661 calls on path objects. There are three ways to instantiate concrete paths:
663 .. class:: Path(*pathsegments)
666 the system's path flavour (instantiating it creates either a
669 >>> Path('setup.py')
672 *pathsegments* is specified similarly to :class:`PurePath`.
676 A subclass of :class:`Path` and :class:`PurePosixPath`, this class
677 represents concrete non-Windows filesystem paths::
682 *pathsegments* is specified similarly to :class:`PurePath`.
686 A subclass of :class:`Path` and :class:`PureWindowsPath`, this class
692 *pathsegments* is specified similarly to :class:`PurePath`.
695 (allowing system calls on non-compatible path flavours could lead to
701 >>> Path('setup.py')
718 call fails (for example because the path doesn't exist).
722 :meth:`~Path.exists()`, :meth:`~Path.is_dir()`, :meth:`~Path.is_file()`,
723 :meth:`~Path.is_mount()`, :meth:`~Path.is_symlink()`,
724 :meth:`~Path.is_block_device()`, :meth:`~Path.is_char_device()`,
725 :meth:`~Path.is_fifo()`, :meth:`~Path.is_socket()` now return ``False``
730 .. classmethod:: Path.cwd()
732 Return a new path object representing the current directory (as returned
735 >>> Path.cwd()
739 .. classmethod:: Path.home()
741 Return a new path object representing the user's home directory (as
742 returned by :func:`os.path.expanduser` with ``~`` construct). If the home
743 directory can't be resolved, :exc:`RuntimeError` is raised.
747 >>> Path.home()
753 .. method:: Path.stat(*, follow_symlinks=True)
755 …Return a :class:`os.stat_result` object containing information about this path, like :func:`os.sta…
756 The result is looked up at each call to this method.
759 ``follow_symlinks=False``, or use :meth:`~Path.lstat`.
763 >>> p = Path('setup.py')
772 .. method:: Path.chmod(mode, *, follow_symlinks=True)
778 argument ``follow_symlinks=False``, or use :meth:`~Path.lchmod`.
782 >>> p = Path('setup.py')
792 .. method:: Path.exists()
794 Whether the path points to an existing file or directory::
796 >>> Path('.').exists()
798 >>> Path('setup.py').exists()
800 >>> Path('/etc').exists()
802 >>> Path('nonexistentfile').exists()
806 If the path points to a symlink, :meth:`exists` returns whether the
810 .. method:: Path.expanduser()
812 Return a new path with expanded ``~`` and ``~user`` constructs,
813 as returned by :meth:`os.path.expanduser`. If a home directory can't be
814 resolved, :exc:`RuntimeError` is raised.
825 .. method:: Path.glob(pattern)
827 Glob the given relative *pattern* in the directory represented by this path,
830 >>> sorted(Path('.').glob('*.py'))
832 >>> sorted(Path('.').glob('*/*.py'))
839 >>> sorted(Path('.').glob('**/*.py'))
850 .. audit-event:: pathlib.Path.glob self,pattern pathlib.Path.glob
856 .. method:: Path.group()
858 Return the name of the group owning the file. :exc:`KeyError` is raised
862 .. method:: Path.is_dir()
864 Return ``True`` if the path points to a directory (or a symbolic link
867 ``False`` is also returned if the path doesn't exist or is a broken symlink;
871 .. method:: Path.is_file()
873 Return ``True`` if the path points to a regular file (or a symbolic link
876 ``False`` is also returned if the path doesn't exist or is a broken symlink;
880 .. method:: Path.is_mount()
882 Return ``True`` if the path is a :dfn:`mount point`: a point in a
884 function checks whether *path*'s parent, :file:`path/..`, is on a different
885 device than *path*, or whether :file:`path/..` and *path* point to the same
886 i-node on the same device --- this should detect mount points for all Unix
892 .. method:: Path.is_symlink()
894 Return ``True`` if the path points to a symbolic link, ``False`` otherwise.
896 ``False`` is also returned if the path doesn't exist; other errors (such
900 .. method:: Path.is_socket()
902 Return ``True`` if the path points to a Unix socket (or a symbolic link
905 ``False`` is also returned if the path doesn't exist or is a broken symlink;
909 .. method:: Path.is_fifo()
911 Return ``True`` if the path points to a FIFO (or a symbolic link
914 ``False`` is also returned if the path doesn't exist or is a broken symlink;
918 .. method:: Path.is_block_device()
920 Return ``True`` if the path points to a block device (or a symbolic link
923 ``False`` is also returned if the path doesn't exist or is a broken symlink;
927 .. method:: Path.is_char_device()
929 Return ``True`` if the path points to a character device (or a symbolic link
932 ``False`` is also returned if the path doesn't exist or is a broken symlink;
936 .. method:: Path.iterdir()
938 When the path points to a directory, yield path objects of the directory
941 >>> p = Path('docs')
953 ``'.'`` and ``'..'`` are not included. If a file is removed from or added
954 to the directory after creating the iterator, whether a path object for
955 that file be included is unspecified.
957 .. method:: Path.lchmod(mode)
959 Like :meth:`Path.chmod` but, if the path points to a symbolic link, the
960 symbolic link's mode is changed rather than its target's.
963 .. method:: Path.lstat()
965 Like :meth:`Path.stat` but, if the path points to a symbolic link, return
969 .. method:: Path.mkdir(mode=0o777, parents=False, exist_ok=False)
971 Create a new directory at this given path. If *mode* is given, it is
973 and access flags. If the path already exists, :exc:`FileExistsError`
974 is raised.
976 If *parents* is true, any missing parents of this path are created
978 *mode* into account (mimicking the POSIX ``mkdir -p`` command).
980 If *parents* is false (the default), a missing parent raises
983 If *exist_ok* is false (the default), :exc:`FileExistsError` is
986 If *exist_ok* is true, :exc:`FileExistsError` exceptions will be
987 ignored (same behavior as the POSIX ``mkdir -p`` command), but only if the
988 last path component is not an existing non-directory file.
994 .. method:: Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)
996 Open the file pointed to by the path, like the built-in :func:`open`
999 >>> p = Path('setup.py')
1006 .. method:: Path.owner()
1008 Return the name of the user owning the file. :exc:`KeyError` is raised
1012 .. method:: Path.read_bytes()
1014 Return the binary contents of the pointed-to file as a bytes object::
1016 >>> p = Path('my_binary_file')
1025 .. method:: Path.read_text(encoding=None, errors=None)
1027 Return the decoded contents of the pointed-to file as a string::
1029 >>> p = Path('my_text_file')
1035 The file is opened and then closed. The optional parameters have the same
1041 .. method:: Path.readlink()
1043 Return the path to which the symbolic link points (as returned by
1046 >>> p = Path('mylink')
1054 .. method:: Path.rename(target)
1056 Rename this file or directory to the given *target*, and return a new Path
1057 instance pointing to *target*. On Unix, if *target* exists and is a file,
1060 *target* can be either a string or another path object::
1062 >>> p = Path('foo')
1065 >>> target = Path('bar')
1071 The target path may be absolute or relative. Relative paths are interpreted
1072 relative to the current working directory, *not* the directory of the Path
1075 It is implemented in terms of :func:`os.rename` and gives the same guarantees.
1078 Added return value, return the new Path instance.
1081 .. method:: Path.replace(target)
1083 Rename this file or directory to the given *target*, and return a new Path
1087 The target path may be absolute or relative. Relative paths are interpreted
1088 relative to the current working directory, *not* the directory of the Path
1092 Added return value, return the new Path instance.
1095 .. method:: Path.absolute()
1097 Make the path absolute, without normalization or resolving symlinks.
1098 Returns a new path object::
1100 >>> p = Path('tests')
1103 >>> p.absolute()
1107 .. method:: Path.resolve(strict=False)
1109 Make the path absolute, resolving any symlinks. A new path object is
1112 >>> p = Path()
1118 "``..``" components are also eliminated (this is the only method to do so)::
1120 >>> p = Path('docs/../setup.py')
1124 If the path doesn't exist and *strict* is ``True``, :exc:`FileNotFoundError`
1125 is raised. If *strict* is ``False``, the path is resolved as far as possible
1126 and any remainder is appended without checking whether it exists. If an
1127 infinite loop is encountered along the resolution path, :exc:`RuntimeError`
1128 is raised.
1131 The *strict* argument (pre-3.6 behavior is strict).
1133 .. method:: Path.rglob(pattern)
1135 This is like calling :func:`Path.glob` with "``**/``" added in front of the
1138 >>> sorted(Path().rglob("*.py"))
1145 .. audit-event:: pathlib.Path.rglob self,pattern pathlib.Path.rglob
1151 .. method:: Path.rmdir()
1156 .. method:: Path.samefile(other_path)
1158 Return whether this path points to the same file as *other_path*, which
1159 can be either a Path object, or a string. The semantics are similar
1160 to :func:`os.path.samefile` and :func:`os.path.samestat`.
1167 >>> p = Path('spam')
1168 >>> q = Path('eggs')
1177 .. method:: Path.symlink_to(target, target_is_directory=False)
1179 Make this path a symbolic link to *target*. Under Windows,
1181 is a directory. Under POSIX, *target_is_directory*'s value is ignored.
1185 >>> p = Path('mylink')
1195 The order of arguments (link, target) is the reverse
1198 .. method:: Path.hardlink_to(target)
1200 Make this path a hard link to the same file as *target*.
1203 The order of arguments (link, target) is the reverse
1208 .. method:: Path.link_to(target)
1210 Make *target* a hard link to this path.
1214 This function does not make this path a hard link to *target*, despite
1216 (target, link) is the reverse of :func:`Path.symlink_to` and
1217 :func:`Path.hardlink_to`, but matches that of :func:`os.link`.
1223 This method is deprecated in favor of :meth:`Path.hardlink_to`, as the
1224 argument order of :meth:`Path.link_to` does not match that of
1225 :meth:`Path.symlink_to`.
1228 .. method:: Path.touch(mode=0o666, exist_ok=True)
1230 Create a file at this given path. If *mode* is given, it is combined
1233 is true (and its modification time is updated to the current time),
1234 otherwise :exc:`FileExistsError` is raised.
1237 .. method:: Path.unlink(missing_ok=False)
1239 Remove this file or symbolic link. If the path points to a directory,
1240 use :func:`Path.rmdir` instead.
1242 If *missing_ok* is false (the default), :exc:`FileNotFoundError` is
1243 raised if the path does not exist.
1245 If *missing_ok* is true, :exc:`FileNotFoundError` exceptions will be
1246 ignored (same behavior as the POSIX ``rm -f`` command).
1252 .. method:: Path.write_bytes(data)
1257 >>> p = Path('my_binary_file')
1263 An existing file of the same name is overwritten.
1268 .. method:: Path.write_text(data, encoding=None, errors=None, newline=None)
1273 >>> p = Path('my_text_file')
1279 An existing file of the same name is overwritten. The optional parameters
1288 -----------------------------------------------
1290 Below is a table mapping various :mod:`os` functions to their corresponding
1291 :class:`PurePath`/:class:`Path` equivalent.
1296 despite having some overlapping use-cases, have different semantics. They
1297 include :func:`os.path.abspath` and :meth:`Path.absolute`,
1298 :func:`os.path.relpath` and :meth:`PurePath.relative_to`.
1301 :mod:`os` and :mod:`os.path` :mod:`pathlib`
1303 :func:`os.path.abspath` :meth:`Path.absolute` [#]_
1304 :func:`os.path.realpath` :meth:`Path.resolve`
1305 :func:`os.chmod` :meth:`Path.chmod`
1306 :func:`os.mkdir` :meth:`Path.mkdir`
1307 :func:`os.makedirs` :meth:`Path.mkdir`
1308 :func:`os.rename` :meth:`Path.rename`
1309 :func:`os.replace` :meth:`Path.replace`
1310 :func:`os.rmdir` :meth:`Path.rmdir`
1311 :func:`os.remove`, :func:`os.unlink` :meth:`Path.unlink`
1312 :func:`os.getcwd` :func:`Path.cwd`
1313 :func:`os.path.exists` :meth:`Path.exists`
1314 :func:`os.path.expanduser` :meth:`Path.expanduser` and
1315 :meth:`Path.home`
1316 :func:`os.listdir` :meth:`Path.iterdir`
1317 :func:`os.path.isdir` :meth:`Path.is_dir`
1318 :func:`os.path.isfile` :meth:`Path.is_file`
1319 :func:`os.path.islink` :meth:`Path.is_symlink`
1320 :func:`os.link` :meth:`Path.hardlink_to`
1321 :func:`os.symlink` :meth:`Path.symlink_to`
1322 :func:`os.readlink` :meth:`Path.readlink`
1323 :func:`os.path.relpath` :meth:`PurePath.relative_to` [#]_
1324 :func:`os.stat` :meth:`Path.stat`,
1325 :meth:`Path.owner`,
1326 :meth:`Path.group`
1327 :func:`os.path.isabs` :meth:`PurePath.is_absolute`
1328 :func:`os.path.join` :func:`PurePath.joinpath`
1329 :func:`os.path.basename` :attr:`PurePath.name`
1330 :func:`os.path.dirname` :attr:`PurePath.parent`
1331 :func:`os.path.samefile` :meth:`Path.samefile`
1332 :func:`os.path.splitext` :attr:`PurePath.stem` and
1338 …] :func:`os.path.abspath` normalizes the resulting path, which may change its meaning in the prese…
1339 …tive_to` requires ``self`` to be the subpath of the argument, but :func:`os.path.relpath` does not.