API¶
Important
The documented methods’ signatures are not always correct.
See path.Path
.
path.py - An object representing a path to a file or directory.
https://github.com/jaraco/path.py
Example:
from path import Path
d = Path('/home/guido/bin')
for f in d.files('*.py'):
f.chmod(0o755)
-
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.-
abspath
()¶ See also
os.path.abspath()
-
access
(mode)¶ Return
True
if current user has access to this path.mode - One of the constants
os.F_OK
,os.R_OK
,os.W_OK
,os.X_OK
See also
os.access()
-
atime
¶ Last access time of the file.
See also
getatime()
,os.path.getatime()
-
bytes
()¶ Open this file, read all bytes, return them as a string.
-
cd
()¶ See also
os.chdir()
-
chdir
()¶ See also
os.chdir()
-
chmod
(mode)¶ Set the mode. May be the new mode (os.chmod behavior) or a symbolic mode.
See also
os.chmod()
-
chown
(uid=-1, gid=-1)¶ Change the owner and group by names rather than the uid or gid numbers.
See also
os.chown()
-
chroot
()¶ See also
os.chroot()
-
chunks
(size, *args, **kwargs)¶ - 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("path.py").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 all stat info (“cp -p 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”.
-
copyfile
(dst, *, follow_symlinks=True)¶ Copy data from src to dst.
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 all stat info (mode bits, atime, mtime, flags) from src to dst.
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=<function copy2>, ignore_dangling_symlinks=False)¶ Recursively copy a directory tree.
The destination directory must not already exist. 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_namesSince 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.
-
ctime
¶ Creation time of the file.
See also
getctime()
,os.path.getctime()
-
dirs
() → List of this directory's subdirectories.¶ The elements of the list are Path objects. This does not walk recursively into subdirectories (but see
walkdirs()
).With the optional pattern argument, this only lists directories whose names match the given pattern. For example,
d.dirs('build-*')
.
-
drive
¶ The drive specifier, for example
'C:'
.This is always empty on systems that don’t use drive specifiers.
-
exists
()¶ See also
os.path.exists()
-
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
os.path.expanduser()
-
expandvars
()¶ See also
os.path.expandvars()
-
ext
¶ The file extension, for example
'.py'
.
-
files
() → List of the files in this directory.¶ The elements of the list are Path objects. This does not walk into subdirectories (see
walkfiles()
).With the optional pattern argument, this only lists files whose names match the given pattern. For example,
d.files('*.pyc')
.
-
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
self.module()
, which defaults toos.path.normcase()
.
See also
fnmatch.fnmatch()
-
get_owner
()¶ Return the name of the owner of this file or directory. Follow symbolic links.
See also
-
classmethod
getcwd
()¶ Return the current working directory as a path object.
See also
os.getcwdu()
-
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
glob.glob()
-
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.isfile() 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.
-
isabs
()¶ See also
os.path.isabs()
-
isdir
()¶ See also
os.path.isdir()
-
isfile
()¶ See also
os.path.isfile()
-
islink
()¶ See also
os.path.islink()
-
ismount
()¶ See also
os.path.ismount()
-
joinpath
= functools.partial(<function Path.joinpath>, <class 'path.Path'>)¶
-
lines
(encoding=None, errors='strict', 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 the content of the file is read as 8-bit characters and returned as a list of (non-Unicode) str objects. - errors - How to handle Unicode errors; see help(str.decode)
- for the options. Default is
'strict'
. - retain - If
True
, retain newline characters; but all newline - character combinations (
'\r'
,'\n'
,'\r\n'
) are translated to'\n'
. IfFalse
, newline characters are stripped off. Default isTrue
.
This uses
'U'
mode.See also
-
link
(newpath)¶ Create a hard link at newpath, pointing to this file.
See also
os.link()
-
listdir
() → List of 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 pattern argument, this only lists items whose names match the given pattern.
-
makedirs
(mode=511)¶ See also
os.makedirs()
-
makedirs_p
(mode=511)¶ Like
makedirs()
, but does not raise an exception if the directory already exists.
-
merge_tree
(dst, symlinks=False, *args, **kwargs)¶ Copy entire contents of self to dst, overwriting existing contents in dst with those in self.
If the additional keyword update is True, each src will only be copied if dst does not exist, or src is newer than dst.
Note that the technique employed stages the files in a temporary directory first, so this function is not suitable for merging trees with large files, especially if the temporary directory is not capable of storing a copy of the entire source tree.
-
mkdir
(mode=511)¶ See also
os.mkdir()
-
module
= <module 'posixpath' from '/usr/lib64/python3.7/posixpath.py'>¶ The path module to use for path operations.
See also
os.path
-
move
(dst, copy_function=<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 the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist.
If the destination 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.
-
mtime
¶ Last-modified time of the file.
See also
getmtime()
,os.path.getmtime()
-
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
basename()
,os.path.basename()
-
namebase
¶ The same as
name()
, but with one file extension stripped off.For example,
Path('/home/guido/python.tar.gz').name == 'python.tar.gz'
, butPath('/home/guido/python.tar.gz').namebase == 'python.tar'
.
-
normcase
()¶ See also
os.path.normcase()
-
normpath
()¶ See also
os.path.normpath()
-
open
(*args, **kwargs)¶ 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.
-
owner
¶ Name of the owner of this file or directory.
See also
-
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
dirname()
,os.path.dirname()
-
pathconf
(name)¶ See also
os.pathconf()
-
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
hashlib.hash.digest()
-
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
hashlib.hash.hexdigest()
-
read_md5
()¶ Calculate the md5 hash for this file.
This reads through the entire file.
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()
,os.readlink()
-
readlinkabs
()¶ Return the path to which this symbolic link points.
The result is always an absolute path.
See also
readlink()
,os.readlink()
-
realpath
()¶ See also
os.path.realpath()
-
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.abspath()
.
-
remove
()¶ See also
os.remove()
-
removedirs
()¶ See also
os.removedirs()
-
removedirs_p
()¶ Like
removedirs()
, but does not raise an exception if the directory is not empty or does not exist.
-
rename
(new)¶ See also
os.rename()
-
renames
(new)¶ See also
os.renames()
-
rmdir
()¶ See also
os.rmdir()
-
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)¶ Recursively delete a directory tree.
If ignore_errors is set, errors are ignored; otherwise, if 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 exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised.
-
samefile
(other)¶ See also
os.path.samefile()
-
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.Path.joinpath(*result)
will yield the original path.
-
splitdrive
() → Return ``(p.drive, <the rest of p>)``.¶ 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
os.path.splitdrive()
-
splitext
() → Return ``(p.stripext(), p.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
os.path.splitext()
-
splitpath
() → Return ``(p.parent, p.name)``.¶
-
splitunc
()¶ See also
os.path.splitunc()
-
statvfs
()¶ Perform a
statvfs()
system call on this path.See also
os.statvfs()
-
stripext
() → Remove one file extension from the path.¶ For example,
Path('/home/guido/python.tar.gz').stripext()
returnsPath('/home/guido/python.tar')
.
-
symlink
(newlink)¶ Create a symbolic link at newlink, pointing here.
See also
os.symlink()
-
text
(encoding=None, errors='strict')¶ Open this file, read it in, return the content as a string.
All newline sequences are converted to
'\n'
. Keyword arguments will be passed toopen()
.See also
-
touch
()¶ Set the access/modified times of this file to the current time. Create the file if it does not exist.
The UNC mount point for this path. This is empty for paths on local drives.
-
unlink
()¶ See also
os.unlink()
-
classmethod
using_module
(module)¶
-
utime
(times)¶ Set the access and modified times of this file.
See also
os.utime()
-
walk
() → 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.isdir()
.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
() → iterator over subdirs, recursively.¶ With the optional pattern argument, this yields only directories whose names match the given pattern. For example,
mydir.walkdirs('*test')
yields only directories with names ending in'test'
.The errors= keyword argument controls behavior when an error occurs. The default is
'strict'
, which causes an exception. The other allowed values are'warn'
(which reports the error viawarnings.warn()
), and'ignore'
.
-
walkfiles
() → iterator over files in D, recursively.¶ The optional argument pattern limits the results to files with names that match the pattern. For example,
mydir.walkfiles('*.tmp')
yields only files with the.tmp
extension.
-
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', linesep='\n', append=False)¶ Write the given lines of text to this file.
By default this overwrites any existing file at this path.
This puts a platform-specific newline sequence on every line. See linesep below.
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.
- linesep - The desired line-ending. This line-ending is
- applied to every line. If a line already has any
standard line ending (
'\r'
,'\n'
,'\r\n'
,u'\x85'
,u'\r\x85'
,u'\u2028'
), that will be stripped off and this will be used instead. The default is os.linesep, which is platform-dependent ('\r\n'
on Windows,'\n'
on Unix, etc.). SpecifyNone
to write the lines as-is, likefile.writelines()
.
Use the keyword argument
append=True
to append lines to the file. The default is to overwrite the file.Warning
When you use this with Unicode data, if the encoding of the existing data in the file is different from the encoding you specify with the encoding= parameter, the result is mixed-encoding data, which can really confuse someone trying to read the file later.
-
write_text
(text, encoding=None, errors='strict', linesep='\n', append=False)¶ 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/unicode - The text to be written.
- encoding - str - The Unicode encoding that will be used.
- This is ignored if text isn’t a Unicode string.
- errors - str - How to handle Unicode encoding errors.
- Default is
'strict'
. Seehelp(unicode.encode)
for the options. This is 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
. You can also specifyNone
to leave all newlines as they are in text. - 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'
).If you don’t like your platform’s default, you can override it using the linesep= keyword argument. If you specifically want
write_text()
to preserve the newlines as-is, uselinesep=None
.This applies to Unicode text the same as to 8-bit text, except there are three additional standard Unicode end-of-line sequences:
u'\x85'
,u'\r\x85'
, andu'\u2028'
.(This is slightly different from when you open a file for writing with
fopen(filename, "w")
in C oropen(filename, 'w')
in Python.)— Unicode
If text isn’t Unicode, then apart from newline handling, the bytes are written verbatim to the file. The encoding and errors arguments are not used and must be omitted.
If text is Unicode, it is first converted to
bytes()
using the specified encoding (or the default encoding if encoding isn’t specified). The errors argument applies only to this conversion.
-
-
class
path.
CaseInsensitivePattern
¶ A string with a
'normcase'
property, suitable for passing tolistdir()
,dirs()
,files()
,walk()
,walkdirs()
, orwalkfiles()
to match case-insensitive.For example, to get all files ending in .py, .Py, .pY, or .PY in the current directory:
from path import Path, CaseInsensitivePattern as ci Path('.').files(ci('*.py'))
-
normcase
¶
-