API¶
Important
The documented methods’ signatures are not always correct.
See path.Path
.
Path Pie
Implements path.Path
- An object representing a
path to a file or directory.
Example:
from path import Path
d = Path('/home/guido/bin')
# Globbing
for f in d.files('*.py'):
f.chmod(0o755)
# Changing the working directory:
with Path("somewhere"):
# cwd in now `somewhere`
...
# Concatenate paths with /
foo_txt = Path("bar") / "foo.txt"
- class path.Path(other='.')¶
Represents a filesystem path.
For documentation on individual methods, consult their counterparts in
os.path
.Some methods are additionally included from
shutil
. The functions are linked directly into the class namespace such that they will be bound to the Path instance. For example,Path(src).copy(target)
is equivalent toshutil.copy(src, target)
. Therefore, when referencing the docs for these methods, assume src references self, the Path instance.- absolute()¶
See also
- access(*args, **kwargs)¶
Return does the real user have access to this path.
>>> Path('.').access(os.F_OK) True
See also
- property atime¶
Last access time of the file.
>>> Path('.').atime > 0 True
Allows setting:
>>> some_file = Path(getfixture('tmp_path')).joinpath('file.txt').touch() >>> MST = datetime.timezone(datetime.timedelta(hours=-7)) >>> some_file.atime = datetime.datetime(1976, 5, 7, 10, tzinfo=MST) >>> some_file.atime 200336400.0
See also
- basename()¶
See also
- bytes()¶
Open this file, read all bytes, return them as a string.
- cd()¶
See also
- chdir()¶
See also
- chmod(mode)¶
Set the mode. May be the new mode (os.chmod behavior) or a symbolic mode.
>>> a_file = Path(getfixture('tmp_path')).joinpath('afile.txt').touch() >>> a_file.chmod(0o700) Path(... >>> a_file.chmod('u+x') Path(...
See also
- chown(uid=-1, gid=-1)¶
Change the owner and group by names or numbers.
See also
- chroot()¶
See also
- chunks(size: int, mode: OpenTextMode = ..., buffering: int = ..., encoding: str | None = ..., errors: str | None = ..., newline: str | None = ..., closefd: bool = ..., opener: Callable[[str, int], int] | None = ...) Iterator[str] ¶
- chunks(size: int, mode: OpenBinaryMode, buffering: int = ..., encoding: str | None = ..., errors: str | None = ..., newline: str | None = ..., closefd: bool = ..., opener: Callable[[str, int], int] | None = ...) Iterator[bytes]
- chunks(size: int, mode: str, buffering: int = ..., encoding: str | None = ..., errors: str | None = ..., newline: str | None = ..., closefd: bool = ..., opener: Callable[[str, int], int] | None = ...) Iterator[str | bytes]
- Returns a generator yielding chunks of the file, so it can
be read piece by piece with a simple for loop.
Any argument you pass after size will be passed to
open()
.- Example:
>>> hash = hashlib.md5() >>> for chunk in Path("NEWS.rst").chunks(8192, mode='rb'): ... hash.update(chunk)
This will read the file by chunks of 8192 bytes.
- copy(dst, *, follow_symlinks=True)¶
Copy data and mode bits (“cp src dst”). Return the file’s destination.
The destination may be a directory.
If follow_symlinks is false, symlinks won’t be followed. This resembles GNU’s “cp -P src dst”.
If source and destination are the same file, a SameFileError will be raised.
- copy2(dst, *, follow_symlinks=True)¶
Copy data and metadata. Return the file’s destination.
Metadata is copied with copystat(). Please see the copystat function for more information.
The destination may be a directory.
If follow_symlinks is false, symlinks won’t be followed. This resembles GNU’s “cp -P src dst”.
- copyfile(dst, *, follow_symlinks=True)¶
Copy data from src to dst in the most efficient way possible.
If follow_symlinks is not set and src is a symbolic link, a new symlink will be created instead of copying the file it points to.
- copymode(dst, *, follow_symlinks=True)¶
Copy mode bits from src to dst.
If follow_symlinks is not set, symlinks aren’t followed if and only if both src and dst are symlinks. If lchmod isn’t available (e.g. Linux) this method does nothing.
- copystat(dst, *, follow_symlinks=True)¶
Copy file metadata
Copy the permission bits, last access time, last modification time, and flags from src to dst. On Linux, copystat() also copies the “extended attributes” where possible. The file contents, owner, and group are unaffected. src and dst are path-like objects or path names given as strings.
If the optional flag follow_symlinks is not set, symlinks aren’t followed if and only if both src and dst are symlinks.
- copytree(dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, dirs_exist_ok=False)¶
Recursively copy a directory tree and return the destination directory.
If exception(s) occur, an Error is raised with a list of reasons.
If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. If the file pointed by the symlink doesn’t exist, an exception will be added in the list of errors raised in an Error exception at the end of the copy process.
You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Notice that this has no effect on platforms that don’t support os.symlink.
The optional ignore argument is a callable. If given, it is called with the src parameter, which is the directory being visited by copytree(), and names which is the list of src contents, as returned by os.listdir():
callable(src, names) -> ignored_names
Since copytree() is called recursively, the callable will be called once for each directory that is copied. It returns a list of names relative to the src directory that should not be copied.
The optional copy_function argument is a callable that will be used to copy each file. It will be called with the source path and the destination path as arguments. By default, copy2() is used, but any function that supports the same signature (like copy()) can be used.
If dirs_exist_ok is false (the default) and dst already exists, a FileExistsError is raised. If dirs_exist_ok is true, the copying operation will continue if it encounters existing directories, and files within the dst tree will be overwritten by corresponding files from the src tree.
- property ctime¶
Creation time of the file.
See also
- classmethod cwd()¶
Return the current working directory as a path object.
See also
- dirname()¶
See also
- dirs(*args, **kwargs)¶
List of this directory’s subdirectories.
The elements of the list are Path objects. This does not walk recursively into subdirectories (but see
walkdirs()
).Accepts parameters to
iterdir()
.
- property drive¶
The drive specifier, for example
'C:'
.This is always empty on systems that don’t use drive specifiers.
- exists()¶
See also
- expand()¶
Clean up a filename by calling
expandvars()
,expanduser()
, andnormpath()
on it.This is commonly everything needed to clean up a filename read from a configuration file, for example.
- expanduser()¶
See also
- expandvars()¶
See also
- files(*args, **kwargs)¶
List of the files in self.
The elements of the list are Path objects. This does not walk into subdirectories (see
walkfiles()
).Accepts parameters to
iterdir()
.
- fnmatch(pattern, normcase=None)¶
Return
True
if self.name matches the given pattern.- pattern - A filename pattern with wildcards,
for example
'*.py'
. If the pattern contains a normcase attribute, it is applied to the name and path prior to comparison.- normcase - (optional) A function used to normalize the pattern and
filename before matching. Defaults to normcase from
self.module
,os.path.normcase()
.
See also
- get_owner()¶
Return the name of the owner of this file or directory. Follow symbolic links.
See also
- getatime()¶
See also
- getctime()¶
See also
- getmtime()¶
See also
- getsize()¶
See also
- glob(pattern)¶
Return a list of Path objects that match the pattern.
pattern - a path relative to this directory, with wildcards.
For example,
Path('/users').glob('*/bin/*')
returns a list of all the files users have in theirbin
directories.See also
Note
Glob is not recursive, even when using
**
. To do recursive globbing seewalk()
,walkdirs()
orwalkfiles()
.
- group(*, follow_symlinks=True)¶
Return the group name of the file gid.
- iglob(pattern)¶
Return an iterator of Path objects that match the pattern.
pattern - a path relative to this directory, with wildcards.
For example,
Path('/users').iglob('*/bin/*')
returns an iterator of all the files users have in theirbin
directories.See also
Note
Glob is not recursive, even when using
**
. To do recursive globbing seewalk()
,walkdirs()
orwalkfiles()
.
- in_place(mode='r', buffering=-1, encoding=None, errors=None, newline=None, backup_extension=None)¶
A context in which a file may be re-written in-place with new content.
Yields a tuple of
(readable, writable)
file objects, where writable replaces readable.If an exception occurs, the old file is restored, removing the written data.
Mode must not use
'w'
,'a'
, or'+'
; only read-only-modes are allowed. AValueError
is raised on invalid modes.For example, to add line numbers to a file:
p = Path(filename) assert p.is_file() with p.in_place() as (reader, writer): for number, line in enumerate(reader, 1): writer.write('{0:3}: '.format(number))) writer.write(line)
Thereafter, the file at filename will have line numbers in it.
- is_dir()¶
See also
- is_file()¶
See also
- isabs()¶
>>> Path('.').isabs() False
See also
- islink()¶
See also
- ismount()¶
>>> Path('.').ismount() False
See also
- iterdir(match=None)¶
Yields items in this directory.
Use
files()
ordirs()
instead if you want a listing of just files or just subdirectories.The elements of the list are Path objects.
With the optional match argument, a callable, only return items whose names match the given pattern.
- joinpath(*others)¶
Join first to zero or more
Path
components, adding a separator character (first.module.sep
) if needed. Returns a new instance offirst._next_class
.See also
- lines(encoding=None, errors=None, retain=True)¶
Open this file, read all lines, return them in a list.
- Optional arguments:
- encoding - The Unicode encoding (or character set) of
the file. The default is
None
, meaning uselocale.getpreferredencoding()
.- errors - How to handle Unicode errors; see
open for the options. Default is
None
meaning “strict”.- retain - If
True
(default), retain newline characters, but translate all newline characters to
\n
. IfFalse
, newline characters are omitted.
- lstat()¶
Like
stat()
, but do not follow symbolic links.>>> Path('.').lstat() == Path('.').stat() True
See also
- makedirs(mode=0o777)¶
See also
- makedirs_p(mode=0o777)¶
Like
makedirs()
, but does not raise an exception if the directory already exists.
- merge_tree(dst, symlinks=False, *, copy_function=shutil.copy2, ignore=lambda dir, contents: ...)¶
Copy entire contents of self to dst, overwriting existing contents in dst with those in self.
Pass
symlinks=True
to copy symbolic links as links.Accepts a
copy_function
, similar to copytree.To avoid overwriting newer files, supply a copy function wrapped in
only_newer
. For example:src.merge_tree(dst, copy_function=only_newer(shutil.copy2))
- mkdir(mode=0o777)¶
See also
- module = <module 'posixpath' (frozen)>¶
The path module to use for path operations.
See also
- move(dst, copy_function=copy2)¶
Recursively move a file or directory to another location. This is similar to the Unix “mv” command. Return the file or directory’s destination.
If dst is an existing directory or a symlink to a directory, then src is moved inside that directory. The destination path in that directory must not already exist.
If dst already exists but is not a directory, it may be overwritten depending on os.rename() semantics.
If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. Symlinks are recreated under the new name if os.rename() fails because of cross filesystem renames.
The optional copy_function argument is a callable that will be used to copy the source or it will be delegated to copytree. By default, copy2() is used, but any function that supports the same signature (like copy()) can be used.
A lot more could be done here… A look at a mv.c shows a lot of the issues this implementation glosses over.
- property mtime¶
Last modified time of the file.
Allows setting:
>>> some_file = Path(getfixture('tmp_path')).joinpath('file.txt').touch() >>> MST = datetime.timezone(datetime.timedelta(hours=-7)) >>> some_file.mtime = datetime.datetime(1976, 5, 7, 10, tzinfo=MST) >>> some_file.mtime 200336400.0
See also
- property name¶
The name of this file or directory without the full path.
For example,
Path('/usr/local/lib/libpython.so').name == 'libpython.so'
See also
- normcase()¶
See also
- normpath()¶
See also
- open(mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)¶
Open this file and return a corresponding file object.
Keyword arguments work as in
io.open()
. If the file cannot be opened, anOSError
is raised.
- property owner¶
Name of the owner of this file or directory.
See also
- property parent¶
This path’s parent directory, as a new Path object.
For example,
Path('/usr/local/lib/libpython.so').parent == Path('/usr/local/lib')
See also
- parts()¶
>>> Path('/foo/bar/baz').parts() (Path('/'), 'foo', 'bar', 'baz')
- pathconf(name)¶
See also
- property permissions: Permissions¶
Permissions.
>>> perms = Path('.').permissions >>> isinstance(perms, int) True >>> set(perms.symbolic) <= set('rwx-') True >>> perms.symbolic 'r...'
- read_bytes()¶
Return the contents of this file as bytes.
- read_hash(hash_name)¶
Calculate given hash for this file.
List of supported hashes can be obtained from
hashlib
package. This reads the entire file.See also
- read_hexhash(hash_name)¶
Calculate given hash for this file, returning hexdigest.
List of supported hashes can be obtained from
hashlib
package. This reads the entire file.See also
- read_md5()¶
Calculate the md5 hash for this file.
This reads through the entire file.
See also
- read_text(encoding=None, errors=None)¶
Open this file, read it in, return the content as a string.
Optional parameters are passed to
open()
.See also
- readlink()¶
Return the path to which this symbolic link points.
The result may be an absolute or a relative path.
See also
- readlinkabs()¶
Return the path to which this symbolic link points.
The result is always an absolute path.
See also
- realpath()¶
See also
- relpath(start='.')¶
Return this path as a relative path, based from start, which defaults to the current working directory.
- relpathto(dest)¶
Return a relative path from self to dest.
If there is no relative path from self to dest, for example if they reside on different drives in Windows, then this returns
dest.absolute()
.
- remove()¶
See also
- removedirs()¶
See also
- removedirs_p()¶
Like
removedirs()
, but does not raise an exception if the directory is not empty or does not exist.
- rename(new)¶
See also
- renames(new)¶
See also
- replace(target_or_old: Path | str, *args) Path ¶
Replace a path or substitute substrings.
Implements both pathlib.Path.replace and str.replace.
If only a target is supplied, rename this path to the target path, overwriting if that path exists.
>>> dest = Path(getfixture('tmp_path')) >>> orig = dest.joinpath('foo').touch() >>> new = orig.replace(dest.joinpath('fee')) >>> orig.exists() False >>> new.exists() True
..seealso::
pathlib.Path.replace()
If a second parameter is supplied, perform a textual replacement.
>>> Path('foo').replace('o', 'e') Path('fee') >>> Path('foo').replace('o', 'l', 1) Path('flo')
..seealso::
str.replace()
- rmdir()¶
See also
- rmdir_p()¶
Like
rmdir()
, but does not raise an exception if the directory is not empty or does not exist.
- rmtree(ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None)¶
Recursively delete a directory tree.
If dir_fd is not None, it should be a file descriptor open to a directory; path will then be relative to that directory. dir_fd may not be implemented on your platform. If it is unavailable, using it will raise a NotImplementedError.
If ignore_errors is set, errors are ignored; otherwise, if onexc or onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is platform and implementation dependent; path is the argument to that function that caused it to fail; and the value of exc_info describes the exception. For onexc it is the exception instance, and for onerror it is a tuple as returned by sys.exc_info(). If ignore_errors is false and both onexc and onerror are None, the exception is reraised.
onerror is deprecated and only remains for backwards compatibility. If both onerror and onexc are set, onerror is ignored and onexc is used.
- samefile(other)¶
See also
- set_atime(value)¶
- set_mtime(value)¶
- property size¶
Size of the file, in bytes.
See also
- special = functools.partial(<class 'path.SpecialResolver'>, <class 'path.Path'>)¶
- splitall()¶
Return a list of the path components in this path.
The first item in the list will be a Path. Its value will be either
os.curdir
,os.pardir
, empty, or the root directory of this path (for example,'/'
or'C:\\'
). The other items in the list will be strings.Path.joinpath(*result)
will yield the original path.>>> Path('/foo/bar/baz').splitall() [Path('/'), 'foo', 'bar', 'baz']
- splitdrive()¶
Return two-tuple of
.drive
and rest without drive.Split the drive specifier from this path. If there is no drive specifier,
p.drive
is empty, so the return value is simply(Path(''), p)
. This is always the case on Unix.See also
- splitext()¶
Return two-tuple of
.stripext()
and.ext
.Split the filename extension from this path and return the two parts. Either part may be empty.
The extension is everything from
'.'
to the end of the last path segment. This has the property that if(a, b) == p.splitext()
, thena + b == p
.See also
- splitpath()¶
Return two-tuple of
.parent
,.name
.See also
- stat(*, follow_symlinks=True)¶
Perform a
stat()
system call on this path.>>> Path('.').stat() os.stat_result(...)
- statvfs()¶
Perform a
statvfs()
system call on this path.See also
- property stem¶
The same as
name()
, but with one file extension stripped off.>>> Path('/home/guido/python.tar.gz').stem 'python.tar'
- stripext()¶
Remove one file extension from the path.
For example,
Path('/home/guido/python.tar.gz').stripext()
returnsPath('/home/guido/python.tar')
.
- property suffix¶
The file extension, for example
'.py'
.
- symlink(newlink=None)¶
Create a symbolic link at newlink, pointing here.
If newlink is not supplied, the symbolic link will assume the name self.basename(), creating the link in the cwd.
See also
- symlink_to(target: str, target_is_directory: bool = False) None ¶
Create a symbolic link at self, pointing to target.
See also
- touch()¶
Set the access/modified times of this file to the current time. Create the file if it does not exist.
- unlink()¶
See also
- classmethod using_module(module)¶
- utime(*args, **kwargs)¶
Set the access and modified times of this file.
See also
- walk(match=None, errors='strict')¶
Iterator over files and subdirs, recursively.
The iterator yields Path objects naming each child item of this directory and its descendants. This requires that
D.is_dir()
.This performs a depth-first traversal of the directory tree. Each directory is returned just before all its children.
The errors= keyword argument controls behavior when an error occurs. The default is
'strict'
, which causes an exception. Other allowed values are'warn'
(which reports the error viawarnings.warn()
), and'ignore'
. errors may also be an arbitrary callable taking a msg parameter.
- walkdirs(*args, **kwargs)¶
Iterator over subdirs, recursively.
- walkfiles(*args, **kwargs)¶
Iterator over files, recursively.
- with_name(name)¶
Return a new path with the name changed.
>>> Path('/home/guido/python.tar.gz').with_name("foo.zip") Path('/home/guido/foo.zip')
- with_stem(stem)¶
Return a new path with the stem changed.
>>> Path('/home/guido/python.tar.gz').with_stem("foo") Path('/home/guido/foo.gz')
- with_suffix(suffix)¶
Return a new path with the file suffix changed (or added, if none)
>>> Path('/home/guido/python.tar.gz').with_suffix(".foo") Path('/home/guido/python.tar.foo')
>>> Path('python').with_suffix('.zip') Path('python.zip')
>>> Path('filename.ext').with_suffix('zip') Traceback (most recent call last): ... ValueError: Invalid suffix 'zip'
- write_bytes(bytes, append=False)¶
Open this file and write the given bytes to it.
Default behavior is to overwrite any existing file. Call
p.write_bytes(bytes, append=True)
to append instead.
- write_lines(lines, encoding=None, errors='strict', *, append=False)¶
Write the given lines of text to this file.
By default this overwrites any existing file at this path.
Puts a platform-specific newline sequence on every line.
lines - A list of strings.
- encoding - A Unicode encoding to use. This applies only if
lines contains any Unicode strings.
- errors - How to handle errors in Unicode encoding. This
also applies only to Unicode strings.
Use the keyword argument
append=True
to append lines to the file. The default is to overwrite the file.
- write_text(text: str, encoding: str | None = None, errors: str = 'strict', linesep: str | None = os.linesep, append: bool = False) None ¶
Write the given text to this file.
The default behavior is to overwrite any existing file; to append instead, use the append=True keyword argument.
There are two differences between
write_text()
andwrite_bytes()
: newline handling and Unicode handling. See below.Parameters:
text - str - The text to be written.
encoding - str - The text encoding used.
- errors - str - How to handle Unicode encoding errors.
Default is
'strict'
. Seehelp(unicode.encode)
for the options. Ignored if text isn’t a Unicode string.- linesep - keyword argument - str/unicode - The sequence of
characters to be used to mark end-of-line. The default is
os.linesep
. SpecifyNone
to use newlines unmodified.- append - keyword argument - bool - Specifies what to do if
the file already exists (
True
: append to the end of it;False
: overwrite it). The default isFalse
.
— Newline handling.
write_text()
converts all standard end-of-line sequences ('\n'
,'\r'
, and'\r\n'
) to your platform’s default end-of-line sequence (seeos.linesep
; on Windows, for example, the end-of-line marker is'\r\n'
).To override the platform’s default, pass the linesep= keyword argument. To preserve the newlines as-is, pass
linesep=None
.This handling applies to Unicode text and bytes, except with Unicode, additional non-ASCII newlines are recognized:
\x85
,\r\x85
, and\u2028
.— Unicode
text is written using the specified encoding (or the default encoding if encoding isn’t specified). The errors argument applies only to this conversion.
- class path.TempDir(*args, **kwargs)¶
A temporary directory via
tempfile.mkdtemp()
, and constructed with the same parameters that you can use as a context manager.For example:
>>> with TempDir() as d: ... d.is_dir() and isinstance(d, Path) True
The directory is deleted automatically.
>>> d.is_dir() False
See also
- class path.masks.Permissions¶
>>> perms = Permissions(0o764) >>> oct(perms) '0o764' >>> perms.symbolic 'rwxrw-r--' >>> str(perms) 'rwxrw-r--' >>> str(Permissions(0o222)) '-w--w--w-'
- property bits¶
- property symbolic¶
- path.masks.compound(mode: str) Callable[[int], int] ¶
Support multiple, comma-separated Unix chmod symbolic modes.
>>> oct(compound('a=r,u+w')(0)) '0o644'
- path.masks.gen_bit_values(number)¶
Return a zero or one for each bit of a numeric value up to the most significant 1 bit, beginning with the least significant bit.
>>> list(gen_bit_values(16)) [0, 0, 0, 0, 1]
- path.masks.padded(iterable, fillvalue=None, n=None, next_multiple=False)¶
Yield the elements from iterable, followed by fillvalue, such that at least n items are emitted.
>>> list(padded([1, 2, 3], '?', 5)) [1, 2, 3, '?', '?']
If next_multiple is
True
, fillvalue will be emitted until the number of items emitted is a multiple of n:>>> list(padded([1, 2, 3, 4], n=3, next_multiple=True)) [1, 2, 3, 4, None, None]
If n is
None
, fillvalue will be emitted indefinitely.
- path.masks.simple(mode: str) Callable[[int], int] ¶
Convert a Unix chmod symbolic mode like
'ugo+rwx'
to a function suitable for applying to a mask to affect that change.>>> mask = simple('ugo+rwx') >>> mask(0o554) == 0o777 True
>>> simple('go-x')(0o777) == 0o766 True
>>> simple('o-x')(0o445) == 0o444 True
>>> simple('a+x')(0) == 0o111 True
>>> simple('a=rw')(0o057) == 0o666 True
>>> simple('u=x')(0o666) == 0o166 True
>>> simple('g=')(0o157) == 0o107 True
>>> simple('gobbledeegook') Traceback (most recent call last): ValueError: ('Unrecognized symbolic mode', 'gobbledeegook')